Get the element type of each index of an array with mixed types

Viewed 133

I have a mixed array like:

const array = [false, 1, '', class T {}];

Whose type is:

type arrayType = typeof array; // (string | number | boolean | typeof T) []

And the type of an object in any index is:

string | number | boolean | typeof T

How can I get the type of the object from a specific index, as below, instead of the union of the types?

const a = array [0] // should be boolean
const b = array [1] // should be number
const c = array [2] // should be string
const d = array [3] // should be typeof T

TS Playground

1 Answers

You need to use a tuple type. You can either be explicit about the type, or you can make TS infer a tuple type by using an as const assertion:

const array = [false,1,''] as const;


type arrayType = typeof array; /// readonly [false, 1, ""]

Playground Link

Related