skip to Main Content
Main Code:

export class TodosComponent implements OnInit{
  todos!: Todo[]; 
  localItem: string;
  constructor(){
    const item = localStorage.getItem("todos");
    this.localItem = item;
    if(this.localItem == null){
      this.todos = [];
    }
    else{
      console.log(this.todos);
      this.todos = JSON.parse("localItem");
    }
  }

This is what I got after compilation
ERROR
src/app/MyComponents/todos/todos.component.ts:14:5 – error TS2322: Type ‘string | null’ is not assignable to type ‘string’.
Type ‘null’ is not assignable to type ‘string’.

14 this.localItem =`your text` item;

I tried by adding,
const localItem: string | null = getValueFromSomewhere();
but it didn’t worked

2

Answers


  1. Reading Items from the localStorage can potential return null (if the key does not exist in the localStorage) therefore localStorage.getItem("todos") could either return a string or null. In your case, you are assigning it to this.localItem which based on your time will always be a string. So you either adjust the type of this.localItem to be string | null or you perform an accurate null check for item first, for example like this:

    export class TodosComponent implements OnInit{
      todos!: Todo[]; 
      localItem: string;
      constructor(){
        const item = localStorage.getItem("todos");
        if(item == null){
          this.todos = [];
        }
        else{
        this.localItem = item;
          console.log(this.todos);
          this.todos = JSON.parse("localItem");
        }
      }
    }
    
    Login or Signup to reply.
  2. As mentioned in Wortmann’s Answer.

    There are multiple ways to handle your case.

    Some of them are :

    1. Changing type of localItem to string|null.
    export class TodosComponent implements OnInit{
      todos!: Todo[]; 
      localItem: string|null;
      constructor(){
        this.localItem = localStorage.getItem("todos");
        if(this.localItem == null){
          this.todos = [];
        }
        else{
          console.log(this.todos);
          this.todos = JSON.parse("localItem");
        }
      }
    1. using ?? operator.
    export class TodosComponent implements OnInit{
      todos!: Todo[]; 
      localItem: string;
      constructor(){
        this.localItem = localStorage.getItem("todos") ?? "";
        if(this.localItem == ""){
          this.todos = [];
        }
        else{
          console.log(this.todos);
          this.todos = JSON.parse("localItem");
        }
      }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search