Reputation: 338
Sorry for the messy title. I guess, providing an example make it more clear.
const array = [
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
];
// A will be the type Array<{ id: number, value: string }>
type A = typeof array;
// K will be the type of all the keys of Array type like length, toString, ...
type K = keyof A;
// I wish the below can make T the type { id: number, value: string }
type T = paramof A;
I know that the example is bit silly since I can just define an interface like { id: number, value: string }
to get T
. But I am in a situation that something like paramof
will be very useful. Please imagine that the array
variable is not on my control.
TypeScript allows us to get the type from a value and to get all the keys from a type. Is there any way to get the type of type parameter from a type that has type parameter, in TypeScript?
Upvotes: 1
Views: 86
Reputation: 250336
In Typescript 2.8 you can easily do this for any specific generic type, not just for arrays using conditional types:
type A = typeof array;
// Get the generic
type AParam = A extends Array<infer T> ? T : never;
In 2.7 or before you can just index the array to get the type of an item:
type A = typeof array;
// Item Of A
type AItem = A[0]
// Or
type AItem2 = typeof array[0]
Upvotes: 1