首页 > 解决方案 > 联合类型的部分键作为打字稿中对象的键

问题描述

我想使用联合类型的键作为打字稿中对象的键。

type EnumType = 'a1' | 'a2'

const object:{[key in EnumType]: string}= {
 a1: 'test'
}

在这种情况下,我必须将 a2 添加为对象中的键。有没有办法使它成为可选的?

操场

标签: javascripttypescripttypes

解决方案


请使用实用程序类型

type EnumType = "a1" | "a2";

const object: Partial<Record<EnumType, string>> = {
  a1: "test",
};


推荐阅读