“联合体类型值到字符串的映射”的打字稿类型?

时间:2020-02-23 17:21:45

标签: javascript typescript dictionary types union

有一个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是字符串联合{{1 }}。

3 个答案:

答案 0 :(得分:2)

您要寻找的类型是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

答案 1 :(得分:0)

您可以使用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',
};

答案 2 :(得分:0)

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

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