Home > Net >  How to get type of key and value of a Map type definition in typescript
How to get type of key and value of a Map type definition in typescript

Time:11-02

Given a type of Map, for example:

type Foo = Map<string, number>;

Is there a way to then get the type that was used for the key and for the value?

CodePudding user response:

You could define a conditional type like this to extract the key and value of any map you want:

type Foo = Map<string, number>;

type MapKey<T> = T extends Map<infer K, any> ? K : never;
type MapValue<T> = T extends Map<any, infer V> ? V : never;

type FooKey = MapKey<Foo>
type FooValue = MapValue<Foo>

// Or if you just need it for the current case:

type FooKey2 = Foo extends Map<infer K, any> ? K : never;
type FooValue2 = Foo extends Map<any, infer V> ? V : never;

CodePudding user response:

A (horrible) way it could be

type Foo = Map<string, number>;

type Key = Parameters<Foo["set"]>[0];
type Value = Parameters<Foo["set"]>[1];
  • Related