TypeScript 具有称为tuples 的“固定长度”数组类型。您可以使用optional tuple elements 来表示一个数组,其长度在某个范围内最多为 4。如果您想尝试保持长度限制,我建议您使用readonly tuple:
type ArrayOfMaxLength4 = readonly [any?, any?, any?, any?];
const a: ArrayOfMaxLength4 = [item1, item2, item3, item4, item5]; // error!
// ~ <-- Source has 5 element(s) but target allows only 4
const b: ArrayOfMaxLength4 = [item1, item2, item3]; // okay
我将“固定长度”放在引号中,因为元组由Array 表示并输入为一种特殊类型的Array,它有像push() 这样可以改变长度的方法。没有什么能阻止您 push将值添加到元组的末尾。
const c: [number, string] = [1, "a"];
c.push(2); // oops
c.unshift("OOPS"); // big oops, totally wrong value in tuple
console.log(c); // ["OOPS", 1, "a", 2]
microsoft/TypeScript#6325 提出了阻止这种情况发生的请求,但被拒绝了。一种更难违反约束的方法是使用 ReadonlyArray 或 readonly 元组,它不公开任何方法来让你改变数组。如果您想在不更改数组长度或元素类型的情况下修改元素,这可能会走得太远,但它至少会警告您push():
b.push(5); // error
//~~~~ <-- Property 'push' does not exist on type 'ArrayOfMaxLength4'
Playground link to code