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!
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
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.
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