우선..
{
"compilerOptions": {
...
"strictNullChecks": true,
...
},
}
tsconfig.json 파일에서 strictNullCheck 옵션을 true로 바꾼다. (혹은 "strict" : true로 써둬도 된다) 이렇게 설정하면 TypeScript 컴파일러는 더 엄격한 규칙을 적용하며, 변수에 대한 null 체크가 강제된다.
HTML 조작시 오류
let title = document.querySelector('#title');
title.innerHTML = '안녕하세요'; // title is possibly Element | null
TypeScript에서 strictNullChecks 옵션이 활성화된 경우, 위 메서드의 반환 타입은 Element | null로 설정된다. 따라서 title 변수의 타입은 Element | null이 된다.
그리고 이렇게 타입이 Element | null로 지정된 변수는 해당 변수를 사용할 때마다 null 체크를 강제받게 된다. 즉, title.innerHTML = '안녕하세요';에서는 title이 null일 수 있으므로 null 체크 없이는 코드가 허용되지 않는다.
해결방법
1. 명시적으로 null 체크
null 체크를 사용하여 명시적으로 처리할 수도 있다.
let title = document.querySelector('#title');
if (title !== null) {
title.innerHTML = '안녕하세요';
} else {
console.error('Element with id "title" not found.');
}
이렇게 하는 이유는 타입스크립트가 런타임에서 발생할 수 있는 잠재적인 오류를 사전에 방지하고 안정성을 향상시키기 위함이다. 때문에 개발자는 명시적으로 null 체크를 수행하여 의도치 않은 오류를 방지할 필요가 있다.
2. optional chaining (?.연산자)
let title = document.querySelector('#title');
title?.innerHTML = '안녕하세요'; // title이 null이면 무시됨
이 코드는 옵셔널 체이닝 연산자 (?.)를 사용하여 title이 null이 아닌 경우에만 innerHTML 속성에 접근한다. 만약 title이 null이면 표현식이 중단되고 할당이 실행되지 않는다.
let title = document.querySelector('#title');
if (title?.innerHTML) {
title.innerHTML = '안녕하세요';
} else {
console.error('id가 "title"인 요소를 찾을 수 없습니다.');
}
위처럼 if-else를 사용하여 더욱 명시적으로 제어할 수도 있다.
3. instanceof 연산자
let title = document.querySelector('#title');
if (title instanceof Element) {
title.innerHTML = '안녕하세요';
} else {
console.error('Element with id "title" not found.');
}
title 변수의 타입을 narrowing하여 사용한다.
(Element 자리에 class를 넣고 title 자리에 object를 넣으면 해당 object가 class의 instance(자식)인지 체크할 수 있어서 가장 많이 쓰게 될 것이라고)
4. as (type assertion)
let title = document.querySelector('#title') as Element;
title.innerHTML = '안녕하세요';
넘 위험하니 자주 쓰지 말자. 타입스크립트 쓰는 이유가 없어짐
출처 : 코딩애플 https://codingapple.com/ / TypeScript Documentation https://www.typescriptlang.org/docs/handbook/2/objects.html
'📘 TypeScript > 개념' 카테고리의 다른 글
| [코딩애플] 타입스크립트에서의 class : constructor, prototype 타입지정 (0) | 2023.12.20 |
|---|---|
| [코딩애플] 타입스크립트 HTML 조작시 주의점 (2) : 더 narrowing하기 (1) | 2023.12.17 |
| [코딩애플] 함수와 object 메서드에 type alias 지정하기 (0) | 2023.12.13 |
| [코딩애플] 타입을 특정 값으로 지정하자 : Literal Types (+ as const) (0) | 2023.12.13 |
| [코딩애플] 타입을 변수에 담자 : type alias (0) | 2023.12.11 |