일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 동적 계획법
- TypeScript
- BFS
- Graph
- git
- Javascript
- vscode
- db
- 그레이들
- 리트코드
- DP
- Database
- 알고리즘
- network
- Redux
- Python
- frontend
- DFS
- 다이나믹 프로그래밍
- react
- 안드로이드
- Data Structure
- LeetCode
- 프로그래머스
- java
- 백준
- CS
- VIM
- 자바
- Algorithm
Archives
- Today
- Total
늘 겸손하게
TypeScript - 타입 가드 본문

단언의 문제점
단언으로 모든 오류를 해결할 순 없다.
function printText(el: Element) {
console.log(el.textContent)
}
const h1 = document.querySelector('h1')
printText(h1);
타입스크립트는 마지막 줄에서 오류를 출력한다.

여기서 단언을 통해 타입스크립트 에러 출력은 막을 수 있지만 실제 코드를 실행해보면 오류가 발생합니다.
function printText(el: Element) {
console.log(el.textContent)
}
const h1 = document.querySelector('h1') as HTMLHeadingElement
printText(h1);

위와 같은 문제 해결은 타입 가드를 통해 가능합니다.
타입 가드
방법 1
간단히 if 조건을 추가해 문제를 해결할 수 있습니다.
function printText(el: Element) {
console.log(el.textContent)
}
const h1 = document.querySelector('h1')
if (h1) {
printText(h1);
}
방법 2
instanceof를 활용합니다.
function printText(el: Element) {
console.log(el.textContent)
}
const h1 = document.querySelector('h1')
if (h1 instanceof HTMLHeadingElement) {
printText(h1);
}
방법 3
typeof 를 사용합니다.
// 타입 가드 (Guards)
function concatToStr(a: (number | string), b: (number | string)) {
let result = 'Result : '
if (typeof a === 'number') {
result += a.toString()
} else {
result += a.toUpperCase()
}
result += ' '
if (typeof b === 'number') {
result += b.toString()
} else {
result += b.toUpperCase()
}
console.log(result)
}
concatToStr(100, "200");
'Programming > TypeScript' 카테고리의 다른 글
TypeScript - 타입 및 할당 단언 (0) | 2023.11.01 |
---|---|
TypeScript - 타입 추론 (Inference) (0) | 2023.10.31 |
TypeScript - 타입 종류 (0) | 2023.10.30 |
TypeScript - 타입스크립트 사용해보기 (0) | 2023.07.04 |
TypeScript - 타입스크립트 사용 이유 (0) | 2023.06.16 |