[英]Conditional assignment in typescript like kotlin when
我開始學習 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"
}
難道沒有更方便的方法來實現這個嗎?
object(或地圖)是一種可能性:
const language = "DE" as const;
const descriptionsByLanguage = {
DE: 'HALLO',
EN: 'HELLO',
// etc
};
const description = descriptionsByLanguage[language];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.