【问题标题】:Mapping the values of a string union type to be the keys of an objec type [duplicate]将字符串联合类型的值映射为对象类型的键[重复]
【发布时间】:2022-01-07 09:41:53
【问题描述】:

给定一个字符串联合类型:

type Fruit = 'apple' | 'banana' | 'pear'

我将如何编写类型声明以将上述映射到一个对象类型,该对象类型以这些字符串值作为其键(其所有值,例如,作为字符串)?

一个类型,如果我手动定义的话,应该是这样的:

type FruitObject = {
  apple:string;
  banana:string;
  pear:string;
}

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    您可以只使用预定义类型Record

    type Fruit = 'apple' | 'banana' | 'pear'
    
    type FruitObject = Record<Fruit, string>
    // {
    //   apple:string;
    //   banana:string;
    //   pear:string;
    // }
    
    
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      相关资源
      最近更新 更多