Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
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:

  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?
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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?

Yes, use .then(…, …) instead of .then(…).catch(…):

await fetch(...).then(res =>
  res.json().then(…)
, e => {
  …
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda