typescript不推断promise.all()推断类型
请向某人解释该ts的原因和机制与a
> string vs 'test'
)的类型与<代码> B 同时。我该如何解决?游乐场为在这里。先感谢您。
(async () => {
const [a]: ['test'] = await Promise.all([Promise.resolve('test')])
// ^ type mismatch here
const b: 'test' = await Promise.resolve('test')
console.log(a, b)
})()
Please explain someone the reason and mechanics of that TS doesn't match the types for a
(string
vs 'test'
) matching those for b
at the same time. How can I solve this? The playground is here. Thank you in advance.
(async () => {
const [a]: ['test'] = await Promise.all([Promise.resolve('test')])
// ^ type mismatch here
const b: 'test' = await Promise.resolve('test')
console.log(a, b)
})()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题似乎是实现
Promise.resolve()
函数。任何实施打字的人都不希望将类型推断出尽可能狭窄。如您所见,当调用
Promise.resolve()
使用字符串字面的字体时,该类型被宽扩大到string
。有趣的是,在给变量的显式类型时,这不会发生。
这种行为似乎在版本3.5上发生了变化,但我仍在寻找解释此功能的变形值。
那么您有什么选择?
Promise.resolve()
时,请使用作为const
。Promise.resolve()
编写自己的包装功能,该功能尊重狭窄类型。Playground
The issue here seems to be the implementation of the
Promise.resolve()
function. Whoever implemented the typing did not want types to be inferred as narrow as they could be.As you can see, when calling
Promise.resolve()
with a string literal, the type is widened tostring
.Interestingly, this does not happen when giving an explicit type to the variable.
This behaviour seemed to change in version 3.5 but I am still looking for the changelog which explains this feature.
So what are your options?
as const
when usingPromise.resolve()
.Promise.resolve()
which respects narrow types.Playground