I want to implement a switch-like function similar to the when
operator in Kotlin in Typescript.
Example usage:
const a = 30;
const b = 10;
const result = when(
{[a < b]: 'somethin'},
{[a > b]: 'somethin else'},
{[a >= b]: 'somethin else 2'},
)
>> result == 'something else'
It returns the value of the first case with condition evaluated to true.
I tried to do something like this:
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;
}
but the TS compiler is complaining with An index signature parameter type must be either 'string' or 'number'.ts(1023)
.
Also, when I try to do something like this:
const foo = {[a > b]: 'something'};
TS is again erroring out with A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
This can easily be done in pure JS since the boolean result in the computed property is automatically coerced (converted to) string.
I could not find any way of doing this online so a settled with doing this instead:
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'],
)
This is fine, but I find the syntax of the first example more pleasing to look at.
Am I missing something or is this limitation of the current spec?