javascript - 联合类型的部分键作为打字稿中对象的键
问题描述
我想使用联合类型的键作为打字稿中对象的键。
type EnumType = 'a1' | 'a2'
const object:{[key in EnumType]: string}= {
a1: 'test'
}
在这种情况下,我必须将 a2 添加为对象中的键。有没有办法使它成为可选的?
解决方案
请使用实用程序类型
type EnumType = "a1" | "a2";
const object: Partial<Record<EnumType, string>> = {
a1: "test",
};
推荐阅读
- authentication - 在 NestJs 中验证 Google JWT
- python - 尝试在 MacBook 上安装 pygame 时如何修复“scrap.c:27:10: fatal error: 'SDL.h' file not found”
- java - 将静态类 var 绑定到非静态实例 var 混淆。创建新对象时有效吗?
- linux - 将对象/文件从一个 AWS s3 存储桶复制到另一个没有来自源存储桶的子文件夹路径
- python - 如何修复遇到“无法分配给函数调用”错误的这行代码?
- javascript - 如何获取带有子目录的根 url
- http - 使用您自己的域创建动态二维码?
- ios - 分阶段推出如何影响应用商店上的当前版本号
- reactjs - 不确定如何在 Laravel 中路由到我的 React 视图
- android - 路由弹出/推送后未调用构建方法