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

时间:2019-08-01 11:34:49

标签: typescript

假设我有这个枚举:

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

是否有任何方法可以强制此对象将所有枚举都包含为键,否则会引发编译错误?

2 个答案:

答案 0 :(得分:1)

您可以只使用映射类型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"
  }
};

答案 1 :(得分:0)

如果愿意,还可以使用const断言并摆脱枚举:

export const translationKeys = {
  resp_action_denied: 'resp_action_denied',
  resp_invalid_request: 'resp_invalid_request',
}
const languages = ['ENG', 'GER'] as const
type RequiredTranslations = { [key in (typeof languages)[number]]: string }

type Translations = {
  [key in keyof typeof translationKeys]: RequiredTranslations
}
const translations: Translations = {
  resp_action_denied: {
    ENG: 'Foo bar',
    GER: 'Ich bin',
  },
  resp_invalid_request: {
    ENG: 'Foo bar',
    GER: 'Ich bin',
  },
}

P.S:您需要打字稿3.4及更高版本