typescript - 打字稿:尝试用功能实现替换三元运算符
问题描述
我正在尝试用功能实现替换三元运算符。很难为下面的代码编写 typescript 类型any
。
- 如何将泛型类型传递给可以接受
thn
orels
的函数参数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>
}
所以得到的返回类型是两个可能分支的联合。
推荐阅读
- swift - 无法识别的选择器发送到实例 Sprite Kit
- wix - 使用 Wix 创建一个安装程序,从 JFrog Artifactory 下载文件
- c# - C#:无法将存储在列表中的值写入控制台
- python - 基于当前行和 N 行之后的计算列
- assembly - 为什么我的第二个数字与我的第三个数字值相同?
- python - 图表已断开:无法在“x”层获得张量“x”张量的值。访问以下先前层没有问题:[]
- javascript - 映射一个数组以创建一个新的对数组
- unit-testing - 如何对语法中的规则进行单元测试
- c - 如何在c中间接设置结构的值?
- ruby - 如何获取数组中元素的最后几个数字?