TypeScript

[TypeScript] Object is possibly 'null'

sungtt 2022. 5. 23. 04:40

 Object is possibly 'null'

 

개요

null일수도 있는 값에 null 예외처리 없이 바로 값에 참조하면 일어나는 오류다.

 

해결 방법

값이 null일 경우에 대한 예외처리를 해주면 된다.

대표적으로 옵셔널체이닝('?')을 많이 사용한다.

 

오류가 난 코드

interface interfaceString { str : string, str2 : number}
const [interfaceStr, setInterfaceStr] = useState<(interfaceString|null) >({str:"인터페이스",str2:1234})
  
  //코드 중략
  
<p>인터페이스를 사용한 상태 타입 선언</p>
<p>{interfaceStr.str}</p>

 

해결 코드

코드는 맨 아랫줄 코드의 옵셔널체이닝만 추가되고 다를게 없다.

interface interfaceString { str : string, str2 : number}
const [interfaceStr, setInterfaceStr] = useState<(interfaceString|null) >({str:"인터페이스",str2:1234})
  
  //코드 중략
  
<p>인터페이스를 사용한 상태 타입 선언</p>
<p>{interfaceStr?.str}</p>

 

참고

https://bobbyhadz.com/blog/typescript-object-is-possibly-null-or-undefined

 

Fix - Object is possibly 'null' or 'undefined' error in TS | bobbyhadz

The "Object is possibly 'null' or 'undefined'" error occurs when we try to access a property on an object that may have a value of `null` or `undefined`. To solve the error, use optional chaining to short-circuit if the reference is nullish, e.g. `person?.

bobbyhadz.com