Typescript类型用于“联合类型值到字符串的映射”?

问题描述 投票:0回答:3

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时,该方法却没有。

有这样定义的类型:type ComponentType ='CPU'| “主板” | '内存'| “ PSU”。我想创建一个可用于映射ComponentType以显示字符串的对象,例如东西...

javascript typescript dictionary types union
3个回答
1
投票

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


0
投票

您可以使用mapped types定义对象:


0
投票

您需要的是带有您的键和接口的枚举:

© www.soinside.com 2019 - 2024. All rights reserved.