Reputation: 1511
I am looking for a way to create new object type based on values from string literal type. I would like to extract each string literal value and used it as a key in newly create type. So far I am stuck in such solution:
export type ExtractRouteParams<T> = string extends T
? Record<string, string>
: { [k in T] : string | number }
type P = ExtractRouteParams<'Id1' | 'Id2'>
It's does what I expect. P has following type
type P = {
Id1: string | number;
Id2: string | number;
}
but unfortunately it throws an error
Type 'T' is not assignable to type 'string | number | symbol'. Type 'T' is not assignable to type 'symbol'.
Solution is done based on that playground
Upvotes: 0
Views: 150
Reputation: 862
Use the built-in PropertyKey
type as generic constraint for T
:
// v-----------------v add here
export type ExtractRouteParams<T extends PropertyKey> = string extends T
? Record<string, string>
: { [k in T] : string | number }
type P = ExtractRouteParams<'Id1' | 'Id2'>
Note: PropertyKey
is just an alias for string | number | symbol
.
Upvotes: 1