본문 바로가기
💻CODING/react. vue

[react] Object is possibly 'null' (ft. typescript, style) 오류 해결

by 코딩하는 갓디노 2021. 9. 6.

Object is possibly 'null'

 

react hooks에서 자바스크립트를 이용해 html element에 접근하여
Object is possibly 'null' 이라는 타입스크립트 오류가 났습니다. 

 

 이유는 객체가 비어 있을 수도 있는데 해당 객체의 내부 프로퍼티나 메소드를 사용할 때 입니다.

 

before

const handleClick = () => {
  let scrollBlock = document.querySelector<HTMLElement>('.scrollBlock');
  scrollBlock.style.backgroundColor = "#F6CB44";
};

 

해결 방법

타입 단언 사용 (type assertion)

const handleClick = () => {
  let scrollBlock = document.querySelector<HTMLElement>('.scrollBlock');
  scrollBlock!.style.backgroundColor = "#F6CB44";
};

 

반응형

댓글