Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the type of values in a map in Typescript?

Tags:

typescript

I cannot find a solution for this anywhere.

Lets say I have

type ObjectRecord = { [key: number]: SomeType }

Now I can have another type

type ValueInObjectRecord = ObjectRecord[number] // SomeType

What if I want to do the same thing with a map?

type MapRecord = Map<number, SomeType>
type ValueInMapRecord = MapRecord[number] // does not work!
like image 489
boy Avatar asked Oct 19 '25 03:10

boy


2 Answers

You will want to make use of type inference in conditional types / infer:

type SomeType = { foo: string }

type MapRecord = Map<number, SomeType>

type ValueInMapRecord = MapRecord extends Map<any, infer I> ? I : never
// type ValueInMapRecord = { foo: string; }

This is a common way to retrieve type constituents and would also have worked with ObjectRecord:

type ValueInObjectRecord = ObjectRecord extends {[key:number]: infer I} ? I : never
// type ValueInObjectRecord = { foo: string; }

Playground code

like image 159
A_blop Avatar answered Oct 22 '25 04:10

A_blop


In general, you can always follow down the props to the place where the generic is actually used. For you example, that would be for example

type ValueInObjectRecord = NonNullable<ReturnType<MapRecord['get']>>

It's not the most elegant solution, but the approach of just going down the rabbit hole until one reaches an actual property of the generic type is a versatile and rather straight-forward solution.

like image 36
NotX Avatar answered Oct 22 '25 04:10

NotX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!