【问题标题】:Create new key value type from string literals types从字符串文字类型创建新的键值类型
【发布时间】:2020-12-19 12:32:31
【问题描述】:

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

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完成的

【问题讨论】:

    标签: typescript string-literals


    【解决方案1】:

    使用内置的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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 2018-12-12
      • 2011-06-23
      • 1970-01-01
      相关资源
      最近更新 更多