簡體   English   中英

布爾值作為 TypeScript 中的對象鍵類型

[英]Boolean value as object key type in TypeScript

我想在 Typescript 中實現類似於 Kotlin 中的when運算符的類似 switch 的函數。

用法示例:

const a = 30;
const b = 10;

const result = when(
   {[a < b]: 'somethin'},
   {[a > b]: 'somethin else'},
   {[a >= b]: 'somethin else 2'},
)

>> result == 'something else'

它返回條件評估為真的第一種情況的值。

我試圖做這樣的事情:

type Case<T> = { [key: boolean]: T };

function when<T>(...cases: Case<T>[]) {
  const index = cases.findIndex(c => c.hasOwnProperty(true));
  return index >= 0 ? cases[index][true] : undefined;
}

但 TS 編譯器抱怨An index signature parameter type must be either 'string' or 'number'.ts(1023)

另外,當我嘗試做這樣的事情時:

const foo = {[a > b]: 'something'};

TS 再次出錯, A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)

這可以在純 JS 中輕松完成,因為計算屬性中的布爾結果會自動強制(轉換為)字符串。

我在網上找不到任何這樣做的方法,所以我決定這樣做:

function when<T>(...cases: [boolean, T][]) {
  const index = cases.findIndex(([condition, _]) => condition);
  return index >= 0 ? cases[index][1] : undefined;
}

when(
   {[a < b]: 'somethin'},
   {[a > b]: 'somethin else'},
   {[a >= b]: 'somethin else 2'},
)

這很好,但我發現第一個示例的語法更令人愉快。

我是否遺漏了什么或者是當前規范的限制?

TypeScript 具有強類型,您不應該期望這種強制。 JavaScript 中的對象鍵必須是字符串或數字。 這就是 TypeScript 要求您不要使用布爾值的原因。 您可以嘗試以下解決方案:

type Case<T> = { [key in "true" | "false"]: T };

但是,您需要注意不能有兩個相同的鍵:請參見下面的示例:

let sampleObject = {
    "true": 'something',
    "false": 'something else',
    "false": 'something else 2'
}

console.log(sampleObject);
// will print { true: "something", false: "something else 2" }
// note that the second value is not available because
// you cannot have 2 "false" keys
```

它必須是字符串:

 {[(a < b).toString()]: 'somethin'},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM