如何为TypeScript接口的属性设置固定长度数组类型?
如何将TypeScript接口中coordinates数组的长度固定为2?
当然可以,最直接的方式是使用元组类型替代普通数组类型,元组能明确指定数组的长度和对应位置的元素类型。
修改后的接口如下:
interface MapCoordinates { type: 'Point'; // 注意和示例代码里的type值保持大小写一致,避免类型错误 coordinates: [number, number]; // 固定长度为2的元组,两个元素均为number类型 }
验证示例代码:
// 符合类型要求,不会报错 const point: MapCoordinates = { type: 'Point', coordinates: [39.807222, -76.984722] }; // 若传入长度不为2的数组,TypeScript会直接报错 // const invalidPoint: MapCoordinates = { type: 'Point', coordinates: [1] }; // 错误:元素数量不足 // const invalidPoint2: MapCoordinates = { type: 'Point', coordinates: [1,2,3] }; // 错误:元素数量过多
如果需要防止数组后续被修改长度,可以使用只读元组:
interface MapCoordinates { type: 'Point'; coordinates: readonly [number, number]; }
这样就能严格限制coordinates数组的长度必须为2,同时保证类型安全。
内容的提问来源于stack exchange,提问作者Lelstz
相关产品推荐
相关产品推荐

