TypeError: Cannot read properties of null (reading 'title') 에러 해결(optional chaining)

김승용·2021년 10월 4일
0

이전에 진행했던 프로젝트에서 에러를 발견했다. 클라이언트에서 el.questionId.title 로 데이터를 받을때 TypeError가 발생하였다.

이 문제를 optional chaining(?.)를 사용하여 해결하였다. 여러단계의 객체를 탐색할 경우 TypeError가 발생하는 경우가 있는데 이는 존재하지 않는 객체가 있을때 생기는 에러이다.

undefined가 뜨는 경우

const user = { name: { first: {} } };

console.log(user.name.first.a);

//undefined

TypeError가 뜨는 경우

const user = { name: {} };

console.log(user.name.first.a);

//TypeError: Cannot read property 'a' of undefined

탐색할 때, 마지막 하나의 객체키값이 없다면 undefined값이 뜨고, 객체키값이 두개 이상 없을때는 TypeError를 띄운다.

opptional chaining(?.)을 사용하면 null, undefined, TypeError모두 undefined로 리턴하기 때문에 에러를 처리할 수 있게 된다. el.questionId?.title 로 바꿔주니 정상 작동하였다.

참고

profile
개발 기록

0개의 댓글