[TypeScript] localStorage에서 데이터를 불러올 때 타입 에러 해결하는 법 (Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.)


[TypeScript] localStorage에서 데이터를 불러올 때 타입 에러 해결하는 법 (Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.)

JSON.parse(localStorage.getItem("treasureList")); 위와 같이 localStorage에서 데이터를 불러온 후 파싱해주는 과정에서 아래와 같은 에러가 발생했다. string | null 타입은 string 타입에 할당할 수 없다는 뜻이다. localStorage는 string이나 null 타입을 반환하는데, JSON.parse는 string을 필요로 하기 때문에 발생하는 에러이다. 따라서 JSON.parse 안의 값이 항상 string이 되도록 수정해줘야 한다. JSON.parse(localStorage.getItem("treasureList") || "{}") 이렇게 localStorage에서 불러온 값이 null이라면 "{}"라는 string 값으로 대신하면서 에러..


원문링크 : [TypeScript] localStorage에서 데이터를 불러올 때 타입 에러 해결하는 법 (Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.)