【问题标题】:Typescript type for "map of union type values to strings"?“联合类型值到字符串的映射”的打字稿类型?
【发布时间】:2020-06-07 10:17:46
【问题描述】:

有一个type 定义如下:type ComponentType = 'CPU' | 'Motherboard' | 'Memory' | 'PSU'

我想创建一个对象,我可以使用它来映射 ComponentType 以显示字符串,例如类似:

  const componentTypeToLabel/*: to do*/ = {
    CPU: 'Computer processing unit',
    Motherboard: 'Motherboard',
    Memory: 'Memory',
    PSU: 'Power supply unit',
  };

然而,另外考虑的是,这个componentTypeToLabel 不会包含ComponentType 的所有可能值,只有一些。

componentTypeToLabel 的类型定义是什么样的?如何定义该类型?如果ComponentTypeenum,我知道该怎么做(相信它会是const componentTypeToLabel: { [key in ComponentType]? : string } = ...),但当ComponentType 是字符串联合type 时不会。

【问题讨论】:

    标签: javascript typescript dictionary types union


    【解决方案1】:

    您要查找的类型是Partial<Record<ComponentType, string>>,或等效的{[K in ComponentType]?: string}

    type ComponentType = 'CPU' | 'Motherboard' | 'Memory' | 'PSU';
    const componentTypeToLabel: Partial<Record<ComponentType, string>> = {
      CPU: 'Computer processing unit',
      Motherboard: 'Motherboard',
      Memory: 'Memory',
      PSU: 'Power supply unit',
    };
    

    PartialRecord 都内置在 mapped types 中;您可以在内联 TypeScript 手册链接中了解更多关于它们的信息。

    希望有所帮助;祝你好运!

    Playground link to code

    【讨论】:

      【解决方案2】:

      您可以使用interface 来定义对象:

      interface IComponentType {
        CPU?: string;
        Motherboard?: string;
        Memory?: string;
        PSU?: string;
      }
      

      由于 componentTypeToLabel 可能不包含所有可能的值,我们可以在接口中使用 ? 将它们定义为可选。

      然后我们可以创建对象类型:

      const componentTypeToLabel:IComponentType = {
        CPU: 'Computer processing unit',
        Motherboard: 'Motherboard',
        Memory: 'Memory',
        PSU: 'Power supply unit',
      };
      

      【讨论】:

      • 感谢您的回复。我没有考虑使用界面,但您显示的这个选项确实有效。欣赏它。
      【解决方案3】:

      你需要的是一个带有你的键和接口的枚举:

      enum ComponentTypes {
          CPU = 'CPU',
          Motherboard = 'Motherboard',
          Memory = 'Memory',
          PSU = 'PSU'}
      
      
      type ComponentType = { [key in ComponentTypes]? : string }
      
      const componentTypeToLabel: ComponentType = {
          CPU: 'Computer processing unit',
          Motherboard: 'Motherboard',
          PSU: 'Power supply unit',
          xxx: 'test'  // <--- Not Allow
      }
      

      Playground

      【讨论】:

      • 感谢您的回复。有多个示例(例如您的示例)会很有帮助。欣赏它。
      猜你喜欢
      • 2021-01-26
      • 2019-12-11
      • 1970-01-01
      • 2018-04-28
      • 2022-01-06
      • 2019-11-19
      • 2022-08-17
      • 1970-01-01
      • 2022-12-07
      相关资源
      最近更新 更多