使用 Promise 的类型“{}"上不存在属性 [英] Property does not exists on type '{}' using Promises

查看:25
本文介绍了使用 Promise 的类型“{}"上不存在属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在访问从已解决的承诺返回的对象的属性.

I am accessing a property of an object returned from a resolved promise.

return new Promise((resolve) => {
    // Get result
    resolve(result)
}).then(r => console.log(r.id))

Typescript 编译代码并且代码工作,但我的 IDE 抱怨 r.id

Typescript compiles the code and the code works but my IDE is complaining about r.id

[ts] 类型{}"上不存在属性id".

[ts] Property 'id' does not exist on type '{}'.

处理这个问题的TypeScript"方法是什么?这个问题 似乎有同样的问题,但我不明白给定的解决方案.这个答案谈到了使用接口,但我不确定如何将其应用于then() Promise

What is the 'TypeScript' method of dealing with this? This question seems to have the same issue but I cannot understand the given solutions. This answer talks about using interfaces but im not sure how I would apply that to the then() function of a Promise

推荐答案

Typescript 将无法通过使用 resolve 来判断 Promise 的结果类型,您需要将结果类型明确指定为 Promise 的泛型参数:

Typescript will not be able to tell the result type of the Promise by the usage of resolve, you need to specify the result type explicitly as a generic parameter to Promise:

new Promise<{ id: string }>((resolve) => {
    // Get result
    resolve(result)
}).then(r => console.log(r.id))

您可以将 { id: string } 替换为任何类型,因为额外的打字稿会检查 resolve 是否使用正确的结果类型调用.

You can replace { id: string } with any type, as bonus typescript will check that resolve is called with the correct result type.

编辑我假设有一些更复杂的代码需要使用 Promise 构造函数而不是 //Get result.如果您已经知道结果,您可以使用 Promse.resolve(result) 它将正确输入承诺,正如@BenjaminGruenbaum 在评论中指出的那样

Edit I am assuming that instead of // Get result there is some more complicated code that requires use of the Promise constructor. If you already know the result, you can just use Promse.resolve(result) which will type the promise correctly as @BenjaminGruenbaum pointed out in the comments

这篇关于使用 Promise 的类型“{}"上不存在属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆