使用承诺,类型"{}"上的属性不存在 [英] Property does not exists on type '{}' using Promises
问题描述
我正在访问从已解决的承诺返回的对象的属性.
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"方法是什么? 这个问题似乎有相同的问题,但我无法理解给定的解决方案. 此答案讨论了使用接口,但不确定如何将其应用于Promise
的then()
功能
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.
修改
我假设不是// Get result
,而是有一些更复杂的代码需要使用Promise
构造函数.如果您已经知道结果,则可以使用Promse.resolve(result)
,它会按照@BenjaminGruenbaum在注释中指出的那样正确键入Promise
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
这篇关于使用承诺,类型"{}"上的属性不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!