首页 > 解决方案 > 字符串类型的参数 | null 不能分配给类型字符串错误的参数

问题描述

当我尝试获取本地存储记录时,它会出现以下错误。

"Argument of type 'string | null' is not assignable to parameter of type 'string'.\n  Type 'null' is not assignable to type 'string'.",

这是代码

this.service.getAllPets(this.CatDog).subscribe(
  data => {
    this.pets = data;
    console.log(data);
    // tslint:disable-next-line:no-bitwise
    const newPet = JSON.parse(localStorage.getItem('newPet'));
    if (newPet){
      this.pets = [newPet, ...this.pets];
    }
    console.log(this.route.snapshot.url.toString());
  }, error => {
    console.log('httperror:');
    console.log(error);
  }
);

标签: typescriptangular11angular-local-storage

解决方案


JSON.parse接受字符串类型的 arg

localStorage.getItem返回字符串类型的 arg 或 null(如果未找到)

因此,您可以在解析之前添加一个快速的默认值集。像这样:

const newPet = JSON.parse(localStorage.getItem('newPet') || "{}");

另一种选择是从本地存储中获取结果,检查它是否不为空,然后解析它。


推荐阅读