首页 > 解决方案 > 提取作为参数传递的承诺类型

问题描述

您好我正在尝试实现这一点:如果我有一个作为参数获取的函数(如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>

标签: typescriptpromisees6-promise

解决方案


您可能想尝试修改您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]

推荐阅读