Property does not exists on type '{}' using Promises

耗尽温柔 提交于 2020-02-04 02:54:14

问题


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 compiles the code and the code works but my IDE is complaining about r.id

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

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


回答1:


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))

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

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



来源:https://stackoverflow.com/questions/49854385/property-does-not-exists-on-type-using-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!