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

TypeScript报错TS2322:Type 'null' 不可分配给类型 'string' 如何解决?

报错原因

Web API 中 localStorage.getItem(key) 方法的返回值类型被 TypeScript 定义为 string | null:当指定 key 对应的存储项存在时返回字符串值,不存在时返回 null。
你声明的类属性 this.localItem 的类型被限定为仅接受 string 类型,无法兼容可能返回的 null 值,因此触发 TS2322 类型不匹配报错:

Error: src/app/MyComponents/todos/todos.component.ts:13:5 - error TS2322: Type 'string | null' is not assignable to type 'string'.
Type 'null' is not assignable to type 'string'.

触发报错的代码行:

this.localItem = localStorage.getItem("todos");
可行解决方法
  • 修改属性类型兼容空值
    将 localItem 的类型声明调整为联合类型,允许接收 null 值:

    // 原声明类似:localItem: string;
    // 修改为:
    localItem: string | null;
    

    后续使用该属性时注意做非空判断即可。

  • 空值兜底默认值
    使用空值合并运算符 ?? 给返回值设置空字符串作为兜底,保证返回值永远是 string 类型:

    this.localItem = localStorage.getItem("todos") ?? "";
    

    当存储项不存在时会自动赋值为空字符串,无需修改原有属性类型。

  • 非空断言(仅确认一定有值时使用)
    如果你100%确定代码执行到此处时,todos 对应的存储项一定存在,不会返回 null,可以用非空断言运算符 ! 告诉 TypeScript 该值不可能为空:

    this.localItem = localStorage.getItem("todos")!;
    

    注意该方式仅跳过类型校验,不会做任何运行时处理,如果实际返回 null 仍可能引发后续逻辑报错。

  • 强制类型转换
    你也可以通过类型断言强制将返回值认定为 string 类型,效果和非空断言类似:

    this.localItem = localStorage.getItem("todos") as string;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:15:04