Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS: how to get constant Array element type

Tags:

typescript

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.

like image 403
Sebastien Lorber Avatar asked May 13 '19 13:05

Sebastien Lorber


2 Answers

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];
like image 160
Titian Cernicova-Dragomir Avatar answered Oct 03 '22 17:10

Titian Cernicova-Dragomir


Can be done easily with:

type MyConstArrayItem = typeof MyConstArray[number]
like image 45
Alexander Danilov Avatar answered Oct 03 '22 16:10

Alexander Danilov