[英]Typescript: How to use key type as enum in an object keep all enum values as optional?
I am using a enum type as key for an object:我使用枚举类型作为 object 的键:
enum Level {
Novice, Intermediate, Pro
}
type Players = { [key in Level] : string[]}
Upon trying to create an object of type players with just Novice and Pro, I get the error saying Intermediate is not present:在尝试仅使用 Novice 和 Pro 创建 object 类型的播放器时,我收到错误消息,提示不存在 Intermediate:
const mapping: Players = {
[Level.Novice]: ["Neo"],
[Level.Pro]: ["John Wick"]
}
How do I make it work?我如何使它工作?
I found out that this can be done by marking the key as optional in the type我发现这可以通过在类型中将键标记为可选来完成
type Players = { [key in Level]? : string[]}
Please notice the '?'请注意“?” which lies outside the
[]
位于
[]
之外
I thought it was a good learning so I shared by answering my own question.我认为这是一个很好的学习,所以我通过回答我自己的问题来分享。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.