0

I am beginning in learning typescript and it's language features. One thing I miss is something like the when expression or a conditional assignment. Something like

val languange = "DE"

val test = when(languange) {
   "DE" -> "HALLO"
   "EN" -> "HELLO"
   else -> "NONE"
}

The only way I found to implement this in typescript was:

const language = "DE"

var description: String;

if (language == "DE") {
   description = "HALLO"
} else if (language == "EN") {
   description = "HELLO"
}

Ain't there a more handy way to implement this?

Andrew
  • 4,264
  • 1
  • 21
  • 65

1 Answers1

5

An object (or Map) is a possibility:

const language = "DE" as const;

const descriptionsByLanguage = {
  DE: 'HALLO',
  EN: 'HELLO',
  // etc
};
const description = descriptionsByLanguage[language];
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Does the language have to be a const? Or is it just optional? – Andrew Mar 27 '21 at 17:45
  • It makes the typings easier. It can also be typed as just a `string`, but then you'll need to check whether the property exists on the object first, or TypeScript won't let you do `descriptionsByLanguage[language]` - either that, or change the type of the object / Map to map strings to strings. – CertainPerformance Mar 27 '21 at 17:48
  • Unfortunately I get the error "Type 'String' cannot be used as an index type." – Andrew Mar 27 '21 at 17:50
  • Are you sure you did `const language = "DE" as const;` as in the answer? If you don't do that, then like I said in the comment, you'll have to check whether the property exists on the object first. – CertainPerformance Mar 27 '21 at 17:50
  • Or sorry I forgot those. But I cant write language as const, because then it says "A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals." I get my language value from a firebase function and therefore cant cast it. What would be the work around? – Andrew Mar 27 '21 at 17:52
  • Then, like I said, you need to check whether the property exists in the object first: https://stackoverflow.com/a/14664748 either that, or change the type of the object to map strings to strings, instead of `'DE' | 'EN'` to values – CertainPerformance Mar 27 '21 at 17:57