Typescript - 매번 null , undefined 체크의 귀찮음
const el:HTMLDivElement | null = document.querySelector('div.toast');
위와 같은 코드가 있다고 할때, 여기서 그냥
el.firstChild
이렇게 쓰면 el 값이 null 일 수 도 있다고 에러를 준다…
그래서 if(el) ~~ 이런식으로 falsy 값 체크를 해주야 되는데
매번 코드를 짤때마다 이 짓을 하기엔 너무 번거롭다.
로직 흐름상 절대로 null 이나 undefined 같은 값이 절대 오지 않는 경우에는
el!.firstChild --> 이처럼 변수 뒤쪽에 느낌표 (assertion operator) 를 써주면 되고
이건 컴파일러에게 "이값은 절대 null , undefined 이 될 수 없으니 그냥 넘어가" 라는 뜻이다.
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 을 리턴해라.