You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错:布尔类型无法赋值给字符串类型参数求助

问题解决:localStorage存储布尔值的类型不匹配报错

错误原因

localStorage.setItem的第二个参数必须是字符串类型,但你代码里的isResult是布尔值(boolean类型),TypeScript的类型检查会阻止这种不匹配的赋值,所以抛出argument of type 'Boolean' is not assignable to type 'string'错误。

解决方案

将布尔值isResult转换为字符串后再存入localStorage,有两种常用方式:

  • 使用String()函数转换
  • 调用布尔值的toString()方法

修改后的完整代码

export const testFunc = (token: string) => {
  const parseValue = (s: string) => s.toLowerCase() === 'true';
  const jwtDecoded = jwtDecode<JwtPayload>(token);

  const isResult = jwtDecoded.isUser ? parseValue(jwtDecoded.isUser) : false;

  // 将布尔值转为字符串后存入localStorage
  localStorage.setItem('local-storage-key', String(isResult));
  // 也可以用:isResult.toString()
  // localStorage.setItem('local-storage-key', isResult.toString());
};

补充说明

后续从localStorage读取该值时,需要把字符串转回布尔值,示例代码:

const storedValue = localStorage.getItem('local-storage-key');
const isUser = storedValue === 'true';

内容的提问来源于stack exchange,提问作者ninja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:02:35