问题
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