typescript - 约束参数函数的返回类型
问题描述
我有一个以函数为参数的函数。参数函数返回几个枚举之一。如何使用参数函数的返回类型来推断包装函数的类型。
我认为作为一个例子更容易解释:
const foo = { a: 1, b: '2' }
function h(k: (() => 'a' | 'b')) {
return foo[k()]
}
const d = h(() => 'a')
// expected: d should be of type number
// actual: d is of type number | string
解决方案
您可以将返回的键类型定义为通用参数(它将被推断为单个键,而不是所有可能键的联合):
function h<K extends keyof typeof foo>(k: (() => K)) {
return foo[k()]
}
const d = h(() => 'a') // now number
推荐阅读
- python - 对混合数据集使用一个热编码和决策树
- php - 使用 curl 发送和 XML base64
- android-studio - 如何在没有用户在场的情况下以编程方式从其他应用程序更新特定的 Google 应用程序
- python - 如何将终端 pip 安装的 tensorflow 导入 pycharm
- blockchain - 从币安区块链获取信息
- php - 如何使用复选框将表中的多行数据插入 MySQL 中的另一个表
- regex - Fluentbit 不解析方括号
- reactjs - react typescript usememo deps 如何处理联合类型?
- laravel - 如何从 Laravel 网站发送通知以响应本机应用程序
- php - 如何在php中创建和启动无限后台脚本?