从字符串文字类型创建新的键值类型

问题描述

我正在寻找一种基于字符串文字类型的值创建新对象类型的方法。我想提取每个字符串文字值并将其用作新创建类型的键。到目前为止,我被困在这样的解决方案中:

export type ExtractRouteParams<T> = string extends T
    ?  Record<string,string>
    : { [k in T] : string | number }

type P = ExtractRouteParams<'Id1' | 'Id2'>

它符合我的预期。 P有以下类型

type P = {
    Id1: string | number;
    Id2: string | number;
}

但不幸的是它抛出了一个错误

类型 'T' 不能分配给类型 'string |数量 |象征'。 类型“T”不可分配给类型“符号”。

解决方案是基于 playground

解决方法

使用内置的 PropertyKey 类型作为 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'>

注意:PropertyKey 只是 string | number | symbol 的别名。

Code example