打字稿限制最大数组长度

时间:2020-12-29 16:18:41

标签: javascript arrays typescript

基本上我想要一个最大长度为 4 的数组类型。 很容易我无法找到如何在打字稿中实现此检查。有人可以帮我吗? 像这样:

const a = [item1, item2, item3, item4, *item5*] -> array has a maximum length of 4

谢谢!

4 个答案:

答案 0 :(得分:3)

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 阻止这种情况发生,但被拒绝了。使违反约束更加困难的一种方法是使用 ReadonlyArrayreadonly 元组,它不会公开任何方法来让您改变数组。如果您想在不更改数组长度或元素类型的情况下修改元素,这可能会走得太远,但它至少会在 push() 之类的事情上警告您:

b.push(5); // error
//~~~~ <-- Property 'push' does not exist on type 'ArrayOfMaxLength4'

Playground link to code

答案 1 :(得分:1)

您可以尝试使用 Object.seal()...当您尝试推送其他元素时,它会引发错误。

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
}

答案 2 :(得分:1)

您正在使用 Typescript,这为您提供了继承的额外好处。解决这个问题的最好方法就是自己写一个:

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
}

答案 3 :(得分:0)

use array.slice(4) 如果您正在处理已存在的数组或 const a = new Array(4)

谢谢。