Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force object to include all enum values as property keys?

Tags:

typescript

Lets assume I have this enum:

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

I use this enum to extract unique string values from single source. Each of them maps to string resolution object:

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

Is there any way to force this object to include all enums as keys otherwise throw compile error?

like image 339
Kunok Avatar asked Jan 21 '26 06:01

Kunok


1 Answers

You can just use the mapped type 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"
  }
};
like image 89
Titian Cernicova-Dragomir Avatar answered Jan 22 '26 19:01

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!