TypeScript:如何在编译时声明固定大小的数组以进行类型检查

问题描述 投票:5回答:3

更新:这些检查用于编译时,而不是在运行时。在我的例子中,失败的案例都是在编译时捕获的,我期待其他应该失败的情况下的类似行为。

假设我正在编写一个类似于表的类,我希望该类的所有成员都是相同长度的数组,如:

class MyClass {
  tableHead:  string[3]; // expect to be a 3 element array of strings
  tableCells: number[3]; // expect to be a 3 element array of numbers
}

到目前为止我找到的最接近的解决方案是:

class MyClass {
  tableHead:  [string, string, string];
  tableCells: [number, number, number];
}

let bar = new MyClass();
bar.tableHead = ['a', 'b', 'c']; // pass
bar.tableHead = ['a', 'b'];      // fail
bar.tableHead = ['a', 'b', 1];   // fail

// BUT these also pass, which are expected to fail at compile time
bar.tableHead = ['a', 'b', 'c', 'd', 'e']; // pass
bar.push('d'); // pass
bar.push('e'); // pass

有更好的想法吗?

javascript typescript typechecking
3个回答
5
投票

更新2:从版本3.4开始,OP要求的内容现在完全可以使用简洁的语法(Playground link):

class MyClass {
  tableHead: readonly [string, string, string]
  tableCells: readonly [number, number, number]
}

更新1:从版本2.7开始,TypeScript现在可以distinguish between lists of different sizes

我不认为可以输入 - 检查元组的长度。 Here是TypeScript作者对此主题的看法。

我认为你所要求的并不是必需的。假设您定义了此类型

type StringTriplet = [string, string, string]

并定义该类型的变量:

const a: StringTriplet = ['a', 'b', 'c']

您不能从该三元组中获得更多变量,例如

const [one, two, three, four] = a;

会出错,而这不符合预期:

const [one, two, three] = a;

我认为缺乏限制长度的能力成为问题的唯一情况是例如当你map超过三胞胎

const result = a.map(/* some pure function */)

并且期望result有3个元素,实际上它可以有3个以上。但是,在这种情况下,你将a视为集合而不是元组,因此这不是元组语法的正确用例。


0
投票

下面是一个控制其内部数组长度的类的简单示例。这不是万无一失的(在获取/设置时你可能想要考虑你是浅层/深层克隆等:

https://jsfiddle.net/904d9jhc/

class ControlledArray {

  constructor(num) {
    this.a = Array(num).fill(0); // Creates new array and fills it with zeros
  }

  set(arr) {
    if (!(arr instanceof Array) || arr.length != this.a.length) {
      return false;
    }
    this.a = arr.slice();
    return true;
  }

  get() {
    return this.a.slice();
  }

}

$( document ).ready(function($) {

  var m = new ControlledArray(3);

  alert(m.set('vera')); // fail
  alert(m.set(['vera', 'chuck', 'dave'])); // pass

  alert(m.get()); // gets copy of controlled array

});

0
投票

来自Typescript: Can I define an n-length tuple type?,以编程方式,具有动态长度:

type Tuple<TItem, TLength extends number> = [TItem, ...TItem[]] & { length: TLength };

type Tuple9<T> = Tuple<T, 9>;
© www.soinside.com 2019 - 2024. All rights reserved.