- Typescript
- Type Guard
타입 가드를 통해 안정성 높이기
Type Guard를 적용하는 방법 알아보기
타입 가드
Type Guard란 데이터의 타입을 알 수 없을 때 혹은 타입이 여러개의 유형이 된다면
조건문을 통해 지정한 타입만 사용하도록 타입에 제한을 두는 것을 Type Guard라 합니다
그럼 한 번 타입 가드를 만들어 보죠
일반적으로 타입을 확인하는 형태는 조건문으로 분기 처리해줍니다.
타입 확인을 위한 4가지 방법
- 1. instanceof를 사용하여 변수가 특정 타입으로부터 생성된 인스턴스와 비교
class Korea {
hello() {
alert("안녕하세요")
}
}
class Japan {
hello() {
alert("こんにちは")
}
}
const lang = (nation: Korea | Japan) => {
if (nation instanceof Korea) {
nation.hello();
}
if (nation instanceof Japan) {
nation.hello();
}
}
- 2. typeof를 사용하여 변수의 타입과 비교
function formatTime(x: number | string): CustomDateType {
if (typeof x === 'string') {
// x가 string 타입일 시
const date = x // ... CustomDateType으로 바꿔줄 어떤 연산
return date
}
const date = x // ... CustomDateType으로 바꿔줄 어떤 연산
const firstLetterOfX = x[0]
// => **Error: There is no guarantee that `x` is a `string`**
return date
}
- 3. in 키워드 사용
interface A {
x: number;
}
interface B {
y: string;
}
function doStuff(q: A | B) {
if ('x' in q) {
// q: A
}
else {
// q: B
}
}
- 4. literal type인 경우 바로 비교
type TriState = 'yes' | 'no' | 'unknown';
function logOutState(state: TriState) {
if (state === 'yes') {
console.log('User selected yes');
} else if (state === 'no') {
console.log('User selected no');
} else {
console.log('User has not made a selection yet');
}
}