In Typescript when I check a variable the then branch infer variable type based on the condition:
type MyType = 'val1' | 'val2' | 'val3'
const variable = 'val1' as MyType
if (variable === 'val2' || variable === 'val3') {
// typeof variable == 'val2' | 'val3'
}
The above code is chatty especially when I check for more than two values and I want to replace it with
if (hasOneOf(variable, 'val2', 'val3')) {
// typeof variable == 'val2' | 'val3'
}
Solution with I'm partially satisfied is:
const hasOneOf = <T, U extends T>(value: T | undefined, ...values: U[]): value is U => value !== undefined && values.indexOf(value as U) >= 0
however it works only when I explicitly define types
if (hasOneOf(variable, 'val2', 'val3')) {
// typeof variable == MyType
}
// vs
if (hasOneOf<MyType, 'val2' | 'val3'>(variable, 'val2', 'val3')) {
// typeof variable == 'val2' | 'val3'
}
Is it possible to create function hasOneOf which infer generic types and returns union defined by parameters ('val2', 'val3' => 'val2' | 'val3') ?