首页 > 解决方案 > 打字稿:尝试用功能实现替换三元运算符

问题描述

我正在尝试用功能实现替换三元运算符。很难为下面的代码编写 typescript 类型any

  1. 如何将泛型类型传递给可以接受thnorels的函数参数functionany other type以便类型检查严格且returns类型正确?
  2. 如何any使用正确类型删除以下代码中的类型?
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)

操场

标签: typescript

解决方案


这是你可以做的:

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

操场

所以得到的返回类型是两个可能分支的联合。


推荐阅读