在其类型签名中指定数组的长度
Specifying an array's length in its type signature
如何在 TypeScript 的类型签名中指定 Array'
s 长度?
declare const a: Array<any>[20]; // wishful syntax
...
foo(a[10]); // fine
foo(a[100]); // type error: index is out of bounds
你不能,因为数组不是固定长度的。过度索引数组不会导致编译时错误。
这是因为 JavaScript 中的数组实际上只是特殊对象,具有更严格定义的 属性 名称和额外的 length
属性。 TypeScript 只改变了数组的一个方面:它们只能包含一种类型的元素。
如今,一个可行的替代方案,至少对于小型阵列来说是 tuple 类型:
declare const t: [boolean, number];
...
t[1] = 5; // fine
t[100] = foo; // error 2493: Tuple type '[boolean, number]' of length '2' has no element at index '100'
如何在 TypeScript 的类型签名中指定 Array'
s 长度?
declare const a: Array<any>[20]; // wishful syntax
...
foo(a[10]); // fine
foo(a[100]); // type error: index is out of bounds
你不能,因为数组不是固定长度的。过度索引数组不会导致编译时错误。
这是因为 JavaScript 中的数组实际上只是特殊对象,具有更严格定义的 属性 名称和额外的 length
属性。 TypeScript 只改变了数组的一个方面:它们只能包含一种类型的元素。
如今,一个可行的替代方案,至少对于小型阵列来说是 tuple 类型:
declare const t: [boolean, number];
...
t[1] = 5; // fine
t[100] = foo; // error 2493: Tuple type '[boolean, number]' of length '2' has no element at index '100'