Angular - onfig.service.ts:11:1 - 错误 TS2532:对象可能是“未定义”

时间:2021-05-25 10:54:55

标签: typescript

在我的 Angular-11 config.service 中,我使用了:

var currentUser = JSON.parse(localStorage.getItem('user'));

我收到此错误:

<块引用>

错误 TS2345:'string 类型的参数 | null' 不能分配给类型为 'string' 的参数。类型 'null' 不能分配给类型 'string'。 10 var currentUser = JSON.parse(localStorage.getItem('user'));

然后当我把它改成:

this.currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');

这个错误变成:

<块引用>

src/app/core/services/config.service.ts:11:1 - 错误 TS2532:对象可能是“未定义”。

<块引用>

11 this.currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');

然后“这个”是下划线

<块引用>

对象可能是“未定义”

如何解决?

谢谢

2 个答案:

答案 0 :(得分:0)

这是正确的方法:

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!) || {};

这是因为:

  • 虽然从 TS 的角度来看 JSON.parse(null) 是无效的,但它仍然有效并且会导致 null
  • 因此 JSON.parse(localStorage.getItem('currentUser')!) 将返回 localstorage 中的对象或 null
  • 最后使用 || {},您声明它肯定会返回一些东西

答案 1 :(得分:0)

我会选择更详细的内容:

const currentUserFromStorage = localStorage.getItem('currentUser') as string; 
const currentUser = !!currentUserFromStorage ? JSON.parse(currentUserFromStorage) : {};