打字稿错误类型“null”不可分配给类型

时间:2021-03-19 18:11:13

标签: javascript angular typescript null local-storage

在我的项目中,我使用 Angular LocalStorage 来存储类型为 Filename 的记录的值。我在 back 方法

中遇到以下错误

错误

Type 'string | null' is not assignable to type 'FileName | undefined'.
  Type 'null' is not assignable to type 'FileName | undefined'.

我需要帮助来解决这个错误,下面是我的代码

代码


export interface FileName {
    fname: number;
    sname: number;
    Tange: number;
    quick: string;
    Mark: string;
    mine: number;
}

currentName: FileName | undefined = undefined;
previousName: FileName | undefined = undefined;

data(rec: FileName, Mark: HTMLTableDataCellElement) {
  const { fname, sname, Tange, record_id, mine } = rec;
  const quick = Mark.innerText;
  this.name.replaceAndNew({sname, Tange, record_id, quick, mine, fname}).subscribe(data => {
    this.process(data);
  })
   localStorage.setItem('FileName', JSON.stringify(rec));
}

back(){
  localStorage.getItem('FileName');
  this.currentName =  localStorage.getItem('FileName'); -----------------> Error

}

4 个答案:

答案 0 :(得分:1)

fortunee 是对的,但是由于 localStorage 中的所有内容都存储为字符串,因此 Typescript 无法保证对象仍然是同一个对象。在这种情况下,您需要通过强制转换告诉 Typescript 解析的对象的类型。

this.currentName =  JSON.parse(localStorage.getItem('FileName') || '{}') as FileName;

之后,您可能需要躲避类型以确保 this.currentName 不是空对象(如果用户清除了他们的 localStorage,则可能会发生这种情况)。

示例:

if (this.currentName.fname == null) {
  // Give the user an error message or something...
  this.currentName = undefined;
}

答案 1 :(得分:1)

如果解析对象时出现错误,您可以使用 try-catch 为其设置默认值

try {
  this.currentName =  JSON.parse(localStorage.getItem('FileName')) as FileName;
} catch(e){
  this.currentName = {}
}

答案 2 :(得分:0)

你需要用 JSON.parse

将它解析回一个对象
this.currentName =  JSON.parse(localStorage.getItem('FileName'));

答案 3 :(得分:0)

我遇到了同样的错误并通过以下方式修复了它:

const currentName =  String(localStorage.getItem('FileName') || '');