gpt4 book ai didi

typescript - 如何强制对象将所有枚举值包含为属性键?

转载 作者:搜寻专家 更新时间:2023-10-30 21:44:53 25 4
gpt4 key购买 nike

假设我有这个枚举:

export enum translationKeys {
resp_action_denied = "resp_action_denied",
resp_invalid_request = "resp_invalid_request",
}

我使用此枚举从单一来源中提取唯一的字符串值。它们每个都映射到字符串解析对象:

const translations: {
[key: string]: RequiredTranslations;
} = {
resp_action_denied: {
ENG: "Foo bar",
GER: "Ich bin"
},
resp_invalid_request: {
ENG: "Baz",
GER: "Das"
},

有没有办法强制这个对象包含所有枚举作为键,否则会抛出编译错误?

最佳答案

您可以只使用映射类型Record:

export enum translationKeys {
resp_action_denied = "resp_action_denied",
resp_invalid_request = "resp_invalid_request",
}

const translations: Record<translationKeys, { ENG: string, GER: string}> = {
resp_action_denied: {
ENG: "Foo bar",
GER: "Ich bin"
},
[translationKeys.resp_invalid_request]: { // can also use computed prop to reference the enum instead of the value.
ENG: "Baz",
GER: "Das"
}
};

关于typescript - 如何强制对象将所有枚举值包含为属性键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57308118/

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