Home > Enterprise >  TypeScript Type 'string | null' is not assignable to type 'string'
TypeScript Type 'string | null' is not assignable to type 'string'

Time:12-14

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;
}

CodePudding user response:

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;
}

CodePudding user response:

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 }
  });
}
  • Related