TypeScript: Argument of type 'string | null' is not assignable t
2023-09-18 14:30 作者:doubleyong | 我要投稿
報(bào)錯(cuò):
? ? Argument of type 'string | null' is not assignable to parameter of type 'string'.
代碼:
?JSON.parse(sessionStorage.getItem("user") ).userId;
原因:
sessionStorage.getItem("user")? 方法可能返回null , 而null 不是字符串 , 則JSON.parse在執(zhí)行時(shí)就會(huì)出錯(cuò),所以typescript 提示了上面的錯(cuò)誤信息,即要處理為null 的情況
解決方案:
JSON.parse(sessionStorage.getItem("user") || "{}" ).userId;
注: 是"{}" 一定要加雙引號(hào)
標(biāo)簽: