Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: how to call json() method on result of promise when result could be of type Response or void?

In my React Native app I make an API call and then try to apply the json() method to the result, like this:

await fetch(...)
  .catch(e => {...})
  .then(res => res.json().then(...)

Typescript throws a warning on json() saying Property 'json' does not exist on type 'void | Response'.

What I Want To Know:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Is there a way to prevent this warning?
  2. If I swap the order of catch and then, the error goes away. But I want catch to catch only errors from fetch(), not from the code in the then block. Is there a way to achieve this?

>Solution :

Use optional chaining:

await fetch(...)
  .catch(e => {...})
  .then(res => res?.json?.().then(...)

The optional chaining operator (?.) enables you to read the value of a
property located deep within a chain of connected objects without
having to check that each reference in the chain is valid.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading