내가 보려고 만든 개발 공부 일지

Typescript - 매번 null , undefined 체크의 귀찮음 본문

Typescript

Typescript - 매번 null , undefined 체크의 귀찮음

kwangsunny 2021. 7. 2. 01:24
const el:HTMLDivElement | null = document.querySelector('div.toast');

위와 같은 코드가 있다고 할때, 여기서 그냥

el.firstChild

이렇게 쓰면 el 값이 null 있다고 에러를 준다…

그래서 if(el) ~~  이런식으로 falsy 체크를 해주야 되는데

매번 코드를 짤때마다 짓을 하기엔 너무 번거롭다.

로직 흐름상 절대로 null 이나 undefined 같은 값이 절대 오지 않는 경우에는

el!.firstChild --> 이처럼 변수 뒤쪽에 느낌표 (assertion operator) 써주면 되고

이건 컴파일러에게 "이값은 절대 null , undefined 이 될 수 없으니 그냥 넘어가" 라는 뜻이다.

 

참고 https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci

 

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

When looking at the sourcecode for a tslint rule, I came across the following statement: if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) { return; } Notice the ! operator after

stackoverflow.com

 

+ 추가적으로 null / undefined 체크 연산자로 물음표 ? 있다.

let x = someObj?.someVal.check();

이런 코드가 있을때, "someObj 가 null 또는 undefined 면 실행을 멈추고 undefined 를 린턴해라" 라는 뜻이다.

 

요약 :

어떤 변수의 내부 값에 접근할때 TS 컴파일러는 항상 null, undefined 체크를 하는데

매번 if 체크하는것은 번거로우니 ! , ? 연산자를 사용한다.

!  :  non-null assertion  -> null, undefined 경우는 없으니 계속 진행해라.

?  : optional chaining  -> null, undefined 이면 undefined 리턴해라.

'Typescript' 카테고리의 다른 글

Typescript 타입추론 & 타입단언  (0) 2021.07.02
Interface vs Type  (0) 2021.07.02
Comments