小编Ili*_*hev的帖子

TypeScript 中布尔值作为对象键类型

when我想在 Typescript 中实现一个类似于 Kotlin 中的运算符的类似 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'
Run Code Online (Sandbox Code Playgroud)

它返回第一个条件评估为 true 的情况的值。

我尝试做这样的事情:

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;
}
Run Code Online (Sandbox Code Playgroud)

但 TS 编译器抱怨An index signature parameter …

javascript pattern-matching typescript

5
推荐指数
1
解决办法
9480
查看次数

标签 统计

javascript ×1

pattern-matching ×1

typescript ×1