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

