Search code examples
arraystypescriptdefinitions

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


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


Solution

  • 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]