HooneyLog
© 2026 Seunghoon Shin. All rights reserved.
모든 게시글
typescript
2022. 5. 20.•
1

Union Type Guard 하는 방법

Seunghoon Shin
작성자 Seunghoon Shin풀스택 개발자

유니온 타입

type DataType = 'income' | 'expense';

해당 유니온 타입에 대한 타입 가드를 하려면 가드를 해주는 함수를 아래와 같이 만들어서 사용이 가능하다

타입 가드를 위한 함수

function isDataType(value: string): value is DataType { return ['income', 'expense'].includes(value as DataType); }

value is DataType 와 같은 리턴타입을 선언해줌으로써 이 유틸함수는 타입 가드를 위한 함수라는것을 명시해준다.

따라서 위 함수의 매개변수 value에 income과 expense가 제외한 다른 값이 들어오면 모두 false로 반환을 한다.

← 이전 글프로그래머스에서 베스트 앨범 풀어보기
다음 글 →Interface에서 어떠한 key의 value를 타입으로 만드는 방법