Stefan
Stefan

Reputation: 1511

Create new key value type from string literals types

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

Answers (1)

A_blop
A_blop

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.

Code example

Upvotes: 1

Related Questions