[英]How to declare array of N elements of custom type in Typescript?
I have created my own type called tuple, and I want to make an array, of length 10, with elements of type tuple.我创建了自己的类型,称为元组,我想创建一个长度为 10 的数组,其中包含元组类型的元素。 How do I do that (possibly) with that specific Array syntax, or any other?
我如何(可能)使用特定的 Array 语法或任何其他语法来做到这一点?
type tuple = [number, number]
var numbers: Array<tuple> = []
Make it a tuple of tuples?使它成为元组的元组? Or specifically, a tuple of the type
tuple
you already have.或者具体来说,您已经拥有的元组类型的
tuple
。
type tuple = [number, number];
const numbers: [tuple, tuple, tuple, tuple, ...] = [...];
Just to add a separate answer if you're okay with having default values for your tuple
, something like this could work:如果您可以为
tuple
设置默认值,只需添加一个单独的答案,这样的事情可能会起作用:
type tuple = [number, number]
type TupleArray<tuple, TupleLen extends number> = [tuple, ...tuple[]] & { length: TupleLen }
let numbers: TupleArray<tuple, 10> = Array(10).fill([0, 0]) as TupleArray<tuple, 10>;
With this approach, you're specifically typing TupleArray
to have a specific length, so there is the added caveat of an empty array or any array above or below a length of 10 would throw an error.使用这种方法,您专门键入
TupleArray
以具有特定的长度,因此添加了空数组或长度大于或小于 10 的任何数组会引发错误的警告。 This is also why you need to fill your array with 10 tuple
s.这也是为什么需要用 10 个
tuple
填充数组的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.