更新:这些检查适用于编译时,而不是运行时。在我的例子中,失败的案例都在编译时被捕获,我期望其他应该失败的案例有类似的行为。
假设我正在编写一个类似表的类,我希望该类的所有成员都是相同长度的数组,例如:
class MyClass {
tableHead: string[3]; // expect to be a 3 element array of strings
tableCells: number[3]; // expect to be a 3 element array of numbers
}
目前我找到的最接近的解决方案是:
class MyClass {
tableHead: [string, string, string];
tableCells: [number, number, number];
}
let bar = new MyClass();
bar.tableHead = ['a', 'b', 'c']; // pass
bar.tableHead = ['a', 'b']; // fail
bar.tableHead = ['a', 'b', 1]; // fail
// BUT these also pass, which are expected to fail at compile time
bar.tableHead = ['a', 'b', 'c', 'd', 'e']; // pass
bar.push('d'); // pass
bar.push('e'); // pass
有什么更好的主意吗?
最佳答案
更新 2:从版本 3.4 开始,OP 要求的内容现在完全可以通过简洁的语法 ( Playground link ) 实现:
class MyClass {
tableHead: readonly [string, string, string]
tableCells: readonly [number, number, number]
}
更新 1:从 2.7 版开始,TypeScript 现在可以 distinguish between lists of different sizes .
我认为不可能对元组的长度进行类型检查。 Here是 TypeScript 作者对此主题的看法。
我认为您所要求的是没有必要的。假设你定义了这个类型
type StringTriplet = [string, string, string]
并定义该类型的变量:
const a: StringTriplet = ['a', 'b', 'c']
您无法从该三元组中获取更多变量,例如
const [one, two, three, four] = a;
会给出一个错误,而这并不像预期的那样:
const [one, two, three] = a;
我认为缺乏限制长度的能力成为问题的唯一情况是例如当你 map
三元组时
const result = a.map(/* some pure function */)
并期望 result
有 3 个元素,而实际上它可以有 3 个以上。但是,在这种情况下,您将 a
视为一个集合而不是一个元组,所以这不是元组语法的正确用例。
关于javascript - TypeScript:如何在编译时声明固定大小的数组以进行类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42441408/