cvss
cvss

Reputation: 511

Typescript: trying to replace ternary operator with functional implementation

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.

  1. How can I pass a generic type to 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?
  2. How can I remove 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)

Playground

Upvotes: 0

Views: 229

Answers (1)

Aleksey L.
Aleksey L.

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>
}

Playground

So the resulting return type is union of both possible branches.

Upvotes: 1

Related Questions