Andrew
Andrew

Reputation: 4712

Conditional assignment in typescript like kotlin when

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?

Upvotes: 0

Views: 520

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

An object (or Map) is a possibility:

const language = "DE" as const;

const descriptionsByLanguage = {
  DE: 'HALLO',
  EN: 'HELLO',
  // etc
};
const description = descriptionsByLanguage[language];

Upvotes: 5

Related Questions