Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'

后端 未结 2 1657
难免孤独
难免孤独 2020-12-13 06:10

I have a dotnetcore 20 and angular4 project that I am trying to create a userService and get the user to my home component. The backend works just fine but the service doesn

相关标签:
2条回答
  • 2020-12-13 06:45

    As the error says, localStorage.getItem() can return either a string or null. JSON.parse() requires a string, so you should test the result of localStorage.getItem() before you try to use it.

    For example:

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

    or perhaps:

    const userJson = localStorage.getItem('currentUser');
    this.currentUser = userJson !== null ? JSON.parse(userJson) : new User();
    

    See also the answer from Willem De Nys. If you are confident that the localStorage.getItem() call can never return null you can use the non-null assertion operator to tell typescript that you know what you are doing:

    this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);
    
    0 讨论(0)
  • 2020-12-13 07:00

    the accepted answer is correct, just wants to add a newer and shorter answer.

    this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);
    
    0 讨论(0)
提交回复
热议问题