koo*_*oos 3 javascript enums types typescript
我使用枚举类型作为对象的键:
enum Level {
Novice, Intermediate, Pro
}
type Players = { [key in Level] : string[]}
Run Code Online (Sandbox Code Playgroud)
在尝试仅使用新手和专业人士创建玩家类型的对象时,我收到错误消息说中级不存在:
const mapping: Players = {
[Level.Novice]: ["Neo"],
[Level.Pro]: ["John Wick"]
}
Run Code Online (Sandbox Code Playgroud)
我该如何让它发挥作用?
我发现这可以通过在类型中将键标记为可选来完成
type Players = { [key in Level]? : string[]}
Run Code Online (Sandbox Code Playgroud)
请注意“?” 位于[]
我认为这是一个很好的学习,所以我通过回答自己的问题来分享。