Property does not exists on type '{}' using Promises
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
myol
Updated on June 17, 2022Comments
-
myol almost 2 years
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 aPromise
-
Benjamin Gruenbaum about 6 yearsOr just call
Promse.resolve(result)
which TypeScript will gladly take care of. -
Titian Cernicova-Dragomir about 6 years@BenjaminGruenbaum true, true, I am assuming there is more code where the
//Get result
comment is, but I will add the simplified version :)