typescript - 如何使密钥可选?
问题描述
这是代码:
type TypeKey = 'A' | 'B' | 'C'
type Types = { [key in TypeKey] : string}
let myTypes : Types = {
A : 'Apple',
B : 'Banna'
}
这将有一个错误:
error: TS2741 [ERROR]: Property 'C' is missing in type '{ A: string; B: string; }' but required in type 'Types'.
如何使'C'可选?谢谢
解决方案
可能有一种更优雅的方式,但您可以通过C
从类型中删除然后将其作为可选属性添加回来来做到这一点:
type TypeKey = 'A' | 'B' | 'C'
// Remove C vvvvv−−−−−−−−−−−−−−−−−−−−−−−−−−−−vvvvvv
type Types = Omit<{ [key in TypeKey] : string}, 'C'> & {C?: string}
// Add it back as an optional property −−−−−−−−−−−−−−^^^^^^^^^^^^^^
let myTypes : Types = {
A : 'Apple',
B : 'Banna'
}
在您问过的评论中:
它有效,但有更好的方法吗?就像是
type TypeKey = 'A' | 'B' | 'C?'
据我所知,没有,但你可以把它转过来,用以下方式定义TypeKey
,Types
而不是相反:
interface Types {
A: string;
B: string;
C?: string;
}
type TypeKey = keyof Types;
let myTypes : Types = {
A : 'Apple',
B : 'Banna'
}
推荐阅读
- c# - 为什么使用 Office 互操作时 Outlook 会崩溃?
- angularjs - 将验证范围附加到正确的输入
- r - 使用for循环获取R中的列表数据框
- python - 使用 spark-submit 运行外部 python 依赖项?
- ios - 如何快速获取相册标题和计数?
- visual-studio-2015 - 数据网格视图中的 For 循环
- python - 无法弄清楚为什么附加到列表不起作用
- javascript - 应该在 setTimeout() 上运行的 Javascript 函数没有被执行
- django - 在for循环中枚举带有标签ol的元素
- for-loop - 在 Octave 中存储来自 for 循环的值