짬짬이기록하기

유니온타입 사용 시 타입 좁히기 본문

Web Development/Typescript

유니온타입 사용 시 타입 좁히기

짬짬이기록하기 2025. 6. 30. 16:21
반응형
1. typeof는 원시타입만 잡아냄(number, bigint, string, boolean, undefined, null)
 

2. instanceof 가 객체타입을 잡아낼 수 있다. (Date 같은 내장객체)
type Period = {
    start: string,
    end: string,
}

function getDayType(day: Period | Date): Date {
    if (day instanceof Date) return day
    return new Date(day.start)
}

console.log(getDayType(new Date("2024-01-01")))
console.log(getDayType({start: "2025-12-31", end: "2026-01-01"}))

 
3. 필드 in 객체 : 객체안에 필드가 있는지 여부 판단
 

4. is : 타입가드함수(리턴이 true이면 변수는 특정타입이다.)
function 타입가드(변수: unknown): 변수 is 특정타입 {
	return 조건식;
}
 
type Rectangle = {width: number, height: number};
type Circle = {radius: number}

// shape is Rectangle : 리턴값이 true이면 shape는 Rectangle 타입이다. false이면 shape는 Rectangle 타입이 아니다.
function isRectangle(shape: unknown): shape is Rectangle {
	// shape as Rectangle : shape의 타입이 Rectangle이라면 width의 값이 undefined가 아니다.
	return (shape as Rectangle).width !== undefined && (shape as Rectangle).height !== undefined
}

function calculateArea(shape: Rectangle | Circle): number {
	if(isRectangle(shape)) {
		return shape.width * shape.height
	} else {
		return Math.PI * shape.radius ** 2
	}
}

console.log(calculateArea({ width: 10, height: 5 }));
console.log(calculateArea({ radius: 7 }));
 
5. type에 식별자를 선언하는 방법
type Track = {
    type: "track", //식별자
    title: string,
    releaseDate: string,
}

type Artist = {
    type: "artist", //식별자
    name: string,
    debutDate: string,
}

const result: Track | Artist = {
    type: "track", // 식별자를 지정해서 진정한 Track 또는 Artist가 선언되도록 함
    title: "hello",
    releaseDate: "2024-01-01"
}

 
6. exhaustiveCheck 완전성 체크 : 아래와 같이 Radio 타입이 추가되는 경우 에러를 일으켜서 추가 조건을 작성할 수 있도록 가이드함
type SearchResult = Track | Artist | Radio;

type Radio = {
    type: "radio",
    title: string,
    numberOfSong: number,
}

function getTypeName(result: SearchResult) {
    if(result.type === "track") return "트랙"
    else if(result.type === "artist") return "아티스트"
    else if(result.type === "radio") return "라디오"
    else {
    	exhaustiveCheck(result); // else if(result.type === "radio") return "라디오" 해당 구문이 없다면, 여기에서 에러를 발생한다. 개발자가 알아차릴 수 있도록함
    	return "결과"
    }
}

function exhaustiveCheck(param: never) { // never : 절대로 발생할 수 없는 값, 즉 여기에 들어오게 된다면 에러가 있는 것임
	throw new Error("error")
}
반응형

'Web Development > Typescript' 카테고리의 다른 글

제네릭 타입  (0) 2025.06.30
기타 type 정리  (0) 2025.06.25
type 정의하기  (0) 2024.12.30