像kotlin这样的字体中的条件赋值



我开始学习typescript及其语言功能。我错过了一件事,比如when表达式或条件赋值。类似的东西

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

我发现在typescript中实现这一点的唯一方法是:

const language = "DE"
var description: String;
if (language == "DE") {
description = "HALLO"
} else if (language == "EN") {
description = "HELLO"
}

难道没有更方便的方法来实现这一点吗?

对象(或Map(是一种可能性:

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

最新更新