提取作为参数传递的承诺类型
Extract promise type passed as parameter
您好,我正在努力实现这一目标:
如果我有一个函数作为参数获取(在我的示例中是 handleRequest(promise: Promise<any>)
的承诺),我想指定任何类型以便 return 正确的类型而不是任何类型。
这是我的尝试:
https://codesandbox.io/s/musing-ives-ougge?fontsize=14&hidenavigation=1&theme=dark
如何获取作为参数传递的 promise 解析的变量类型?
编辑:如 link- 中所述
期望的结果:x 必须获得
的类型
[Point,undefined] |[undefined,PromiseError]
和
传递给函数 handleRequest 的 promise 参数必须是
类型
promise: Promise<the type of the passed 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]
您好,我正在努力实现这一目标:
如果我有一个函数作为参数获取(在我的示例中是 handleRequest(promise: Promise<any>)
的承诺),我想指定任何类型以便 return 正确的类型而不是任何类型。
这是我的尝试:
https://codesandbox.io/s/musing-ives-ougge?fontsize=14&hidenavigation=1&theme=dark
如何获取作为参数传递的 promise 解析的变量类型?
编辑:如 link- 中所述 期望的结果:x 必须获得
的类型[Point,undefined] |[undefined,PromiseError]
和
传递给函数 handleRequest 的 promise 参数必须是
promise: Promise<the type of the passed 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]