【发布时间】:2020-07-06 08:22:19
【问题描述】:
您好,我正在努力实现这一目标:
如果我有一个作为参数获取的函数(在我的示例中类似于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<number>
【问题讨论】:
-
那么您在此处添加的链接为什么不能满足您在此处寻找的内容?既然您使用泛型传递类型,为什么不在最后将其转换为 T 呢?
-
我不想传递类型,我希望它从promise中提取出来
-
我已经为您简化了问题typescriptlang.org/play?jsx=0#code/… 这里的问题是为什么我们在解构后丢失了
Point。答案是:因为PromiseError目前在结构上与anything 兼容。只需添加一些道具declare class PromiseError { message: string } -
当然,我想你想知道它为什么不工作...给你codesandbox.io/s/white-cloud-31qpz?file=/src/index.ts
-
你会得到一个数组而不是元组。看看typescriptlang.org/docs/handbook/release-notes/…
标签: typescript promise es6-promise