4

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 Answer 1

5
+50

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

Sign up to request clarification or add additional context in comments.

1 Comment

@MuratKaragöz it is a marker for the TS compiler to change the way it does inference, namely, it will keep literal type, it will keep tuples, and it will make the tuple readonly github.com/Microsoft/TypeScript/pull/29510

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.