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
TS2339: Property 'then' does not exist on type ' { type: string; payload: Promise< {}>; }' It sounds like I need to include Promise<...> somewhere as a type so typescript knows that then is in fact a property on the object that's returned by dispatcher () but I haven't been able to remove the error.
The "Property does not exist on type ' {}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names. Copied!
[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 Show activity on this post.
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: You can replace { id: string } with any type, as bonus typescript will check that resolve is called with the correct result type.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With