Given an object, in TypeScript it's easy to figure out what the type of the values is-just use T[keyof T]
:
type MyRec = Record<string, number>;
type MyRecValue = MyRec[keyof MyRec]; // number
What is the equivalent of T[keyof T]
for Map
? Is there something built in to the TS standard library?
CodePudding user response:
You can examine the return type of .get
to see what type it returns and get the value. You can also examine the argument type .get
accepts to get the key.
const m = new Map<number, string>();
type M = typeof m;
type Key = Parameters<M["get"]>[0]; // number
type Value = ReturnType<M["get"]; // string | undefined
CodePudding user response:
There is no built-in type to to this. You need to write your own helper:
type ValueOfMap<M extends Map<unknown, unknown>> = M extends Map<unknown, infer V> ? V : never
Now it will work:
type MyMap = Map<string, number>;
type MyMapValue = ValueOfMap<MyMap>; // number
Thanks to this answer for helping me figure it out: https://stackoverflow.com/a/60737746/2697506