将LocalStorage映射到接口

huangapple go评论104阅读模式
英文:

Map LocalStorage to Interface

问题

我从本地存储中检索对象:

  1. retrieveToken(): JwtToken {
  2. return JSON.parse(localStorage.getItem(_key));
  3. }

我需要将存储在本地存储中的数据映射到我的接口:

  1. export interface JwtToken {
  2. access_token: string;
  3. expires_in: number;
  4. token_type: string;
  5. refresh_token: string;
  6. }

我尝试过:

  1. return JSON.parse(localStorage.getItem(_key) as JwtToken);
  2. return JSON.parse<JwtToken>(localStorage.getItem(_key));

任何帮助将不胜感激。

英文:

I'm retrieving an object from local storage:

  1. retrieveToken(): JwtToken {
  2. return JSON.parse(localStorage.getItem(_key));
  3. }

I need to map the data stored in local storage to my interface

  1. export interface JwtToken {
  2. access_token: string;
  3. expires_in: number;
  4. token_type: string;
  5. refresh_token: string;
  6. }

I've tried:

  1. return JSON.parse(localStorage.getItem(_key) as JwtToken);
  2. return JSON.parse&lt;JwtToken&gt;(localStorage.getItem(_key));

Any help would be appreciated

答案1

得分: 2

You're performing your cast on the string value retrieved from storage instead of casting the result of JSON.parse().

It should be:

  1. return JSON.parse(localStorage.getItem(_key)) as JwtToken;

To get rid of the error caused by the fact that localStorage.getItem() potentially returns null, you can add a non-null assertion to convince the compiler that the value for _key will definitely be present in localStorage:

  1. return JSON.parse(localStorage.getItem(_key)!) as JwtToken;

Or, better yet, perform an explicit null check:

  1. const jwtTokenString = localStorage.getItem(_key);
  2. if (jwtTokenString) {
  3. return JSON.parse(jwtTokenString) as JwtToken;
  4. }
英文:

You're performing your cast on the string value retrieved from storage instead of casting the result of JSON.parse().

It should be:

  1. return JSON.parse(localStorage.getItem(_key)) as JwtToken;

To get rid of the error caused by the fact that localStorage.getItem() potentially returns null, you can add a non-null assertion to convince the compiler that the value for _key will definitely be present in localStorage:

  1. return JSON.parse(localStorage.getItem(_key)!) as JwtToken;

Or, better yet, perform an explicit null check:

  1. const jwtTokenString = localStorage.getItem(_key);
  2. if (jwtTokenString) {
  3. return JSON.parse(jwtTokenString) as JwtToken;
  4. }

huangapple
  • 本文由 发表于 2023年3月1日 13:29:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75599901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定