how to limit array's type in specific order in typescript

1.8k Views Asked by At

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

2

There are 2 best solutions below

0
Lajos Gallay On BEST ANSWER

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]
0
Estus Flask On

It can be done with intersection type:

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

const arr: OrderedArray<any> = ['string', 0, ...];