英文:
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<JwtToken>(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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论