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

新手上路,请多包涵

在我的项目中,我使用 Angular LocalStorage 来存储文件名类型的记录值。我在 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

}

原文由 Tejas Mehta 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 336
2 个回答

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;
}

原文由 user2867288 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

原文由 Tanuwo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题