我试图用功能实现取代三元操作符。发现很难为下面写any
的代码编写typescript类型。
- 如何将泛型类型传递给
thn
或els
函数参数,该参数可以接受function
或any other type
,从而使类型检查严格并且returns
是正确的类型? - 我如何删除
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)
游乐场
你可以这样做:
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>
}
游乐场
因此结果返回类型是两个可能分支的并集。