타입 단언 (type assetion)
타입스크립트가 추론 및 분석한 타입을 우리가 원하는 대로 얼마든지 바꿀 때 사용 (프로그래머가 타입스크립트보다 변수 유형에 더 잘 이해하고 있을 때 사용함)
| 1
2
 | const bodyEle = document.querySelector("body");
bodyEle.innerText = "Hello World~";
 | 
bodyEle가 null일 수도 있다는 오류가 발생, 이 때 bodyEle는 HTMLBodyElement라고 타입을 지정하면 오류가 사라짐
1. as로 타입 단언하기
| 1
2
 | const bodyEle = document.querySelector("body") as HTMLBodyElement;
bodyEle.innerText = "Hello World~";
 | 
2. 타입 가드 사용하기
| 1
2
3
4
 | const bodyEle2 = document.querySelector("body");
if (bodyEle2) {
  bodyEle2.innerText = "Hello World~";
}
 | 
3.! 사용
undefined나 null이 아니라고 타입스크립트에게 명시
| 1
2
 | const bodyEle1 = document.querySelector("body");
bodyEle1!.innerText = "Hello World~";
 | 
잘못된 예
| 1
2
3
 | function func(arg: string | null) {
  return (arg as string).toLowerCase();
}
 | 
arg가 null이면 타입 오류 발생!
 Cannot read properties of null
| 1
2
3
4
5
6
7
 | // 타입 가드 사용해서 수정하기
function funcc(arg: string | null) {
  if (arg !== null) {
    return arg.toLowerCase();
  }
}
 |