Adino Prz
Adino Prz

Reputation: 21

Element implicitly has an 'any' type because expression of type... when using a function which requires type string

I'm doing an Angular with express backend aplication. The backend gives me a response like this

console.log(res) -->

{
    "ok": true,
    "msg": "Login ok",
    "auth": "xxxxxxxxxxxx"
}

Now that i have my response i'm trying to save it in a localStorage

localStorage.setItem('auth', res['auth']); //also tried res.get('auth');

However setItem receives string as first element, and string as second element and i keep getting the following error:

Element implicitly has an 'any' type because expression of type ""auth"" cannot be used to index type "Object".

Upvotes: 2

Views: 109

Answers (1)

Gabriel Rouleau
Gabriel Rouleau

Reputation: 110

You could create an interface and set your backend response type to it like so :

export interface BackEndResponse{
    ok: boolean;
    message: string;
    auth: string;
}

I don't know how you're querying your backend but here is an example subscribing to the method that makes the request and return the object as an observable,

setLocalStorage(): void {
    this.yourBackEndService.getBackEndInfo().subscribe((backEndResponse) => {
      localStorage.setItem('auth', backEndResponse.auth);
      // ...
    });
  }

Upvotes: 1

Related Questions