简体   繁体   中英

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. How do I do that (possibly) with that specific Array syntax, or any other?

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.

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:

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. This is also why you need to fill your array with 10 tuple s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM