Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!