0

I have an interface :

export interface Me {
  id: number;
  email: string;
}

I have my component :

export class MyComponent implements OnInit {
   me: Me;  
   ngOnInit() {
       this.me = JSON.parse(localStorage.getItem('me'));
       console.log(this.me);
   }
}

And in console I have :

{
  "id": 11,
  "lastname": "lastname",
  "firstname": "firstname",
  "email": "@mail.ru",
  "enable": true
}

Normally I should have only the fields : id, email. But I get the whole response from /me api call. Have you an idea how I can cast the interface to the reponse from localStorage ? Thx in advance.

SGalea
  • 712
  • 9
  • 18
user2993914
  • 7
  • 2
  • 6
  • @SGalea thank you, I want to do like this because I'm thinking that will be a clean way to get properties using Me interface...so no solution in this case ? – user2993914 Aug 09 '19 at 10:22
  • Typescript is only there to catch errors at compilation time. It doesn't do anything extra than JavaScript. Interfaces compile to nothing. https://www.typescriptlang.org/play/#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgWTwG8AoORAEwC44kBXAWwCM0BuMuYBzBAGxoDOMKMgDm7AL5A – SGalea Aug 09 '19 at 10:26
  • You can defined a property or variable of type `Me`, and then instantiate it with the values from local storage? The very same way you would do it in JavaScript – wentjun Aug 09 '19 at 10:29

0 Answers0