Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid type "string | null" of template literal expression. while sending authorization

Ts-eslint stopped me with the message "Invalid type "string | null" of template literal expression" when I was trying to execute authorization.

The value came from localstorage so it has to be null or string but also I have to combine it with Bearer.

   onMounted(async ()=>{
      let myToken = localStorage.getItem('token');
      
      await axios.post(
        'http://localhost:3000/getdocuments', 
        {headers:{'Authorisation':`Baerer ${myToken}`}}
      )
      .then((res)=>{
          console.log(res);
      })
      .catch(err=>{
          console.log(err);
      })
    })

like image 422
Jane Jacek Avatar asked Aug 08 '26 07:08

Jane Jacek


2 Answers

I think this request should be called only if token is present

onMounted(async ()=>{
      let myToken = localStorage.getItem('token');
      if (!myToken) {
        console.warn('token is empty');
      } else {
        await axios.post(
          'http://localhost:3000/getdocuments', 
          {headers:{'Authorisation':`Baerer ${myToken}`}}
        )
        .then((res)=>{
            console.log(res);
        })
        .catch(err=>{
            console.log(err);
        })
      }
    })
like image 176
Jackkobec Avatar answered Aug 09 '26 20:08

Jackkobec


Sorry this is late, but ran into the same error and just fixed it using a null guard check.

After you grab your token,

if (!myToken) {
    // Error handle
}
like image 44
TLS Avatar answered Aug 09 '26 20:08

TLS