假设我有这个枚举:

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"
  },

是否有任何方法强制此对象将所有枚举包含为键,否则抛出编译错误?

最佳答案

您可以使用映射类型:

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"
  }
};

09-30 19:15