基本上我想要一个最大长度为4的数组类型。很容易,我找不到如何在 TypeScript 中实现此检查的方法。有人可以帮帮我吗?类似于这样:
const a = [item1, item2, item3, item4, *item5*] -> array has a maximum length of 4
谢谢!
基本上我想要一个最大长度为4的数组类型。很容易,我找不到如何在 TypeScript 中实现此检查的方法。有人可以帮帮我吗?类似于这样:
const a = [item1, item2, item3, item4, *item5*] -> array has a maximum length of 4
谢谢!
TypeScript有称为元组的“固定长度”数组类型。您可以使用可选元组元素表示其长度在某个范围内,最多为4的数组。如果您想尝试保持长度限制,则建议使用readonly
元组:
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]
ReadonlyArray
或readonly
元组,它们不公开任何方法来让您改变数组。如果您想修改元素而不改变数组长度或元素类型,则可能会走得太远,但至少可以在诸如push()
之类的情况下发出警告:b.push(5); // error
//~~~~ <-- Property 'push' does not exist on type 'ArrayOfMaxLength4'
class FixedArrad<T> extends Array<T> {
constructor(public readonly max: number) {
super();
}
public push(value: T): number {
if (super.length !== this.max) {
return super.push(value);
}
throw new Error('Reached max capacity');
}
// Etc
}
var arr: number[] = new Array(4);
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
Object.seal(arr); //Can make changes to the existing elements remaining part of it is immutable
for (var i = 0; i < arr.length; i++) {
arr[i] = i * 3
console.log(arr[i])
}
arr.push(20); //Error inserting an element into the array (Find it in the console)
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]) //Prints only 4 elements
}
array.slice(4)
,或者 const a = new Array(4)
。谢谢。