본문 바로가기
프로그래밍/타입스크립트

타입스크립트 - 사용자 정의 타입 가드

by Programmer.Junny 2025. 2. 14.
type Dog = {
    name: string,
    isBark: boolean,
}

type Cat = {
    name: string,
    isScratch: boolean,
}

type Animal = Dog | Cat;

Animal 과 같은 서로소 유니온 타입을 만들었다고 가정해보자.

function warning(animal: Animal) {
    if ('isBark' in animal) {
        animal
    } else if ('isScratch' in animal) {
        animal
    }
}

이런식으로 animal을 Dog나 Cat타입으로 구분하는 것은 사용자의 실수를 유발할 수 있으므로 옳지 않다.

사용자 정의 타입 가드

// 사용자 정의 타입 가드
function isDog(animal: Animal): animal is Dog {
    return (animal as Dog).isBark !== undefined;
}

function isCat(animal: Animal): animal is Cat {
    return (animal as Cat).isScratch !== undefined;
}

이에 이와 같은 '사용자 정의 타입 가드' 를 만들어 사용할 수 있다.

만약 반환값이 true라면 함수 옆에 ': animal is Dog' 가 실행된다.

function warning(animal: Animal) {
    if (isDog(animal)) {
        animal
    } else if (isCat(animal)) {
        animal
    }
}

최종적으로 이렇게 타입을 변환하여 사용할 수 있다.

최근댓글

최근글

skin by © 2024 ttuttak