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
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 tothis.localItem
which based on your time will always be a string. So you either adjust the type ofthis.localItem
to bestring | null
or you perform an accurate null check for item first, for example like this:As mentioned in Wortmann’s Answer.
There are multiple ways to handle your case.
Some of them are :
??
operator.