13

I'm using TS 3.4.5 with the const assertion. How can I retrieve the type of the elements of the declared constant array variable?

export type GetArrayElementType<T extends Array<any>> = T extends (infer U)[] ? U : never;

export const MyConstArray = [
  'item1',
  'item2',
  'item3',
] as const;

export type MyConstArrayItem = GetArrayElementType<typeof MyConstArray>;

I'd like to have as output:

export type MyConstArrayItem = "item1" | "item2" | "item3"

I'm not totally sure how to extract the type information of the items because due to the const assertion, my array is not an array type anymore but is a constant tuple, so GetArrayElementType can't be applied on it.

3

2 Answers 2

29

If you want to use a conditional type you have to keep in mind that as const generates readonly arrays. So this should work as you expect it to:

export type GetArrayElementType<T extends readonly any[]> = T extends readonly (infer U)[] ? U : never;

export const MyConstArray = [
  'item1',
  'item2',
  'item3',
  'item4',
] as const;

export type MyConstArrayItem = GetArrayElementType<typeof MyConstArray>;

But the simpler solution is to not use a conditional type. Type index queries work better here:

export const MyConstArray = [
  'item1',
  'item2',
  'item3',
  'item4',
] as const;

export type MyConstArrayItem = typeof MyConstArray[number];
Sign up to request clarification or add additional context in comments.

Comments

10

Can be done easily with:

type MyConstArrayItem = typeof MyConstArray[number]

1 Comment

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.