0

how to limit array's type in specific order in typescript instead of defining paradigm.

that means, in ts, we just declare a array definition like:

const arr:Array<any> = []

I want get a specific order in definition array,like:

const arr = ['string', 0, ...];

value can only be string tyoe at position 0, and can only be number type at position 1...

thanks

yungcho
  • 23
  • 5

2 Answers2

3

If you want to limit the size to 2 elements you can achieve this with a tuple

const myTuple: [string, number] = ['test', 3]

or extracted the tuple type definition into a type

type myTupleType = [string, number]
const myTuple2: myTupleType = ['test', 3]
Lajos Gallay
  • 1,169
  • 7
  • 16
1

It can be done with intersection type:

type OrderedArray<T> = Array<T> & {
    0?: string;
    1?: number;
}

const arr: OrderedArray<any> = ['string', 0, ...];
Estus Flask
  • 206,104
  • 70
  • 425
  • 565