基本上我想要一种最大长度为 4 的数组。
很容易我无法找到如何在 typescript 中实现此检查。有人可以帮我吗?
像这样的东西:
const a = [item1, item2, item3, item4, *item5*] -> array has a maximum length of 4
谢谢!
最佳答案
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
表示和键入。 , 它有像 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
tuple 不公开任何方法来让你改变数组。如果您想在不更改数组长度或元素类型的情况下修改元素,这可能会走得太远,但它至少会警告您 push()
之类的事情。 :b.push(5); // error
//~~~~ <-- Property 'push' does not exist on type 'ArrayOfMaxLength4'
Playground link to code
关于javascript - typescript 限制最大数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65495285/