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 …