Home > Software engineering >  How to declare array of N elements of custom type in Typescript?
How to declare array of N elements of custom type in Typescript?

Time:09-23

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> = []

CodePudding user response:

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, ...] = [...];

CodePudding user response:

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 tuples.

  • Related