TypeScript:如何在编译时声明固定大小的数组以进行类型检查 [英] TypeScript: how to declare array of fixed size for type checking at Compile Time

查看:37
本文介绍了TypeScript:如何在编译时声明固定大小的数组以进行类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:这些检查是为了编译时,而不是运行时.在我的示例中,所有失败案例都是在编译时捕获的,我期望其他 should-fail 案例也具有类似的行为.

Update: These checks are meant for compile time, not at runtime. In my example, the failed cases are all caught at compile time, and I'm expecting similar behaviour for the other should-fail cases.

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

Suppose I'm writing a table-like class where I want all members of the class to be arrays of the same length, something like:

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
}

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

The closest solution I've found so far is:

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

还有更好的主意吗?

推荐答案

更新2:从版本3.4开始,使用简洁的语法(

Update 2: From version 3.4, what the OP asked for is now fully possible with a succinct syntax (Playground link):

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

更新1:从2.7版开始,TypeScript现在可以

Update 1: From version 2.7, TypeScript can now distinguish between lists of different sizes.

我认为不可能对元组的长度进行类型检查.这里是TypeScript的作者对此主题的看法.

I don't think it's possible to type-check the length of a tuple. Here's the opinion of TypeScript's author on this subject.

我认为您的要求不是必需的.假设您定义了这种类型

I'd argue that what you're asking for is not necessary. Suppose you define this type

type StringTriplet = [string, string, string]

并定义该类型的变量:

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

例如,您无法从该三元组中获得更多变量.

You can't get more variables out of that triplet e.g.

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

将给出错误,而这与预期不符:

will give an error whereas this doesn't as expected:

const [one, two, three] = a;

我认为缺乏限制长度的能力成为问题的唯一情况是当您在三元组上 map

The only situation where I think the lack of ability to constrain the length becomes a problem is e.g. when you map over the triplet

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

,并且期望 result 包含3个元素,而实际上它可以包含3个以上的元素.但是,在这种情况下,您将 a 视为一个集合,而不是一个无论如何,都是元组,所以这不是元组语法的正确用例.

and expect that result have 3 elements when in fact it can have more than 3. However, in this case, you are treating a as a collection instead of a tuple anyway so that's not a correct use case for the tuple syntax.

这篇关于TypeScript:如何在编译时声明固定大小的数组以进行类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆