【问题标题】:Typescript restrict maximum Array Length打字稿限制最大数组长度
【发布时间】:2020-12-29 16:18:41
【问题描述】:

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

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

谢谢!

【问题讨论】:

标签: javascript arrays typescript


【解决方案1】:

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

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

Playground link to code

【讨论】:

    【解决方案2】:

    您可以尝试使用 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
    }

    【讨论】:

      【解决方案3】:

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

      谢谢。

      【讨论】:

        【解决方案4】:

        您正在使用 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
        }
        

        【讨论】:

          猜你喜欢
          • 2018-02-13
          • 1970-01-01
          • 2016-07-22
          • 2021-10-23
          • 1970-01-01
          • 1970-01-01
          • 2023-01-30
          • 2020-03-26
          • 2016-10-30
          相关资源
          最近更新 更多