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.
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];
Can be done easily with:
type MyConstArrayItem = typeof MyConstArray[number]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With