Reputation: 511
I am trying to replace a ternary operator with functional implementation. Finding it hard to write the typescript type for the below code where any
is written.
thn
or els
function param which can accept a function
or any other type
, so that the type checking is strict and returns
the correct type?any
type in the below code with correct types?interface Predicate {
(...args: any): boolean;
}
const ifThenElse = (bool: boolean | Predicate) => (thn: any) => (els: any) : any => {
if(bool) {
if(typeof thn === 'function') {
return thn()
}
return thn
}
if(typeof els === 'function') {
return els()
}
return thn
}
var coffeesToday = ifThenElse(true)(3)(1);
var coffeesTomorrow = ifThenElse(false)(() => 3)( () => 4);
console.log('coffeesToday', coffeesToday)
console.log('coffeesTomorrow', coffeesTomorrow)
Upvotes: 0
Views: 229
Reputation: 37918
Here's what you could do:
type Result<T> = T extends (...args: any[]) => infer R ? R : T
const ifThenElse = (bool: boolean | Predicate) => <T>(thn: T) => <E>(els: E): Result<T> | Result<E> => {
if (bool) {
if (typeof thn === 'function') {
return thn()
}
return thn as Result<T> | Result<E>
}
if (typeof els === 'function') {
return els()
}
return els as Result<T> | Result<E>
}
So the resulting return type is union of both possible branches.
Upvotes: 1