gpt4 book ai didi

javascript - typescript :如何在对象中使用键类型作为枚举,将所有枚举值保持为可选?

转载 作者:行者123 更新时间:2023-12-02 01:48:44 36 4
gpt4 key购买 nike

我使用枚举类型作为对象的键:

enum Level {
Novice, Intermediate, Pro
}

type Players = { [key in Level] : string[]}

尝试创建一个只有 Novice 和 Pro 的玩家类型的对象时,我收到错误提示 Intermediate is not present:

const mapping: Players = {
[Level.Novice]: ["Neo"],
[Level.Pro]: ["John Wick"]
}

如何让它发挥作用?

最佳答案

我发现这可以通过在类型中将键标记为可选来完成

type Players = { [key in Level]? : string[]}

请注意'?'它位于 []

之外

我认为这是一个很好的学习,所以我通过回答我自己的问题来分享。

关于javascript - typescript :如何在对象中使用键类型作为枚举,将所有枚举值保持为可选?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70596237/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com