typescript - 提取作为参数传递的承诺类型
问题描述
您好我正在尝试实现这一点:如果我有一个作为参数获取的函数(如handleRequest(promise: Promise<any>)
我的示例中的承诺),我想指定任何类型以返回正确的类型而不是任何类型。这是我的尝试:
https://codesandbox.io/s/musing-ives-ougge?fontsize=14&hidenavigation=1&theme=dark
如何获取作为参数传递的承诺解析的变量类型?
编辑:如链接中所述 - 所需结果:x 必须获得类型
[Point,undefined] |[undefined,PromiseError]
并且传递给函数handleRequest的promise参数必须是类型
promise: Promise<the type of the passed promise>
例如,如果传递给函数的 Promise 正在解析一个数字,则 Promise 参数必须是:promise: Promise<number>
解决方案
您可能想尝试修改您handleRequest
的如下:
const handleRequest = <T>(promise: Promise<T>): Promise<[T | PromiseError, undefined]> => {
return promise
.then((data): [T, undefined] => [data, undefined])
.catch((error): [PromiseError, undefined] => [error, undefined]);
};
使用上面的示例代码,结果变量的类型为[PromiseError | Point, undefined]
:
const x = await handleRequest(p()); // [PromiseError | Point, undefined]
推荐阅读
- c - 当我硬编码非零最小值时,为什么我的选择排序会失败?
- mongodb - Mongo DB 限制与聚合
- r - 如何从二进制文件中提取数据作为栅格
- spring-boot - Apache Camel 不打印 FTP 日志
- elasticsearch - kafka connect elasticsearch连接器(接收器)数据(几乎)实时移动
- javascript - 类型“PromiseConstructor”.ts(2339) 上不存在属性“allSettled”
- sql - SQL Server - 未使用的 LEFT JOIN 影响执行计划
- angular - 未定义的 contants.ts API 值
- jquery - 当容器可见时如何使用jquery获取单选按钮的选中值
- bash - zsh:我在 bash 上运行良好的 shell 脚本不适用于 zsh