将LocalStorage映射到接口

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

Map LocalStorage to Interface

问题

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

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

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

export interface JwtToken {
  access_token: string;
  expires_in: number;
  token_type: string;
  refresh_token: string;
}

我尝试过:

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

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

任何帮助将不胜感激。

英文:

I'm retrieving an object from local storage:

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

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

export interface JwtToken {
  access_token: string;
  expires_in: number;
  token_type: string;
  refresh_token: string;
}

I've tried:

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

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:

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:

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

Or, better yet, perform an explicit null check:

const jwtTokenString = localStorage.getItem(_key);

if (jwtTokenString) {
    return JSON.parse(jwtTokenString) as JwtToken;
}
英文:

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

It should be:

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:

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

Or, better yet, perform an explicit null check:

const jwtTokenString = localStorage.getItem(_key);

if (jwtTokenString) {
    return JSON.parse(jwtTokenString) as JwtToken;
}

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:

确定