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

232
Visualizações
TypeScript Type 'string | null' is not assignable to type 'string'

In this fragment I Have the next error :

Type 'string | null' is not assignable to type 'string'.
  Type 'null' is not assignable to type 'string'.  TS2322
export async function GetCertainCoinByType(coinId: string) {
  const response = await axios.get(URLofCertainCoins + `certain/${coinId}`, {
      headers : {
          token : localStorage.getItem('token'),
      }
  });
  return response;
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

That's because the return type of Local storage is string | null, and not just string. To avoid this exception, you can first get the item from local storage and then use it like:

export async function GetCertainCoinByType(coinId: string) {
  let tokenFromStorage = localStorage.getItem('token')
  if (!tokenFromStorage ) { 
    throw new Error("no token supplied"); 
  }
  const response = await axios.get(URLofCertainCoins + `certain/${coinId}`, 
  {
      headers : {
          token : tokenFromStorage 
      }
  });
  return response;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

First, check whether token is null, and if it is, exit the function.

Now response is a Promise anyway, since it's returned by an async function. You don't need to await Axios, then re-convert it to a Promise afterwards. You can directly return axios.get(...) and since this removes the only await, it turns out you don't even need the async/await syntax at all here.

export function GetCertainCoinByType(coinId: string): Promise<any> {

  const token:string|null = localStorage.getItem('token');

  if(!token){
    console.log("No token!");
    return ;
  }

  return axios.get(URLofCertainCoins + `certain/${coinId}`, {
      headers : { token }
  });
}
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