참치코더의 꿈 메모장

TypeScript / 타입 좁히기(Type Narrowing) 정리 본문

TypeScript

TypeScript / 타입 좁히기(Type Narrowing) 정리

참치깡 2025. 11. 27. 15:44
728x90

 

타입 좁히기는 값의 타입을 더 구체적으로 추론하도록 만드는 과정이다.

예를 들어, String / number 처럼 유니온 타입일때, 실제 실행 흐름에서 타입을 점점 특정 타입으로 

좁혀 나가는 방식이다.

 

typeof (타입 가드)

 

- 기본적인 타입 좁히기 방식이다.

 

function print(value: string | number) {

  if(typeof value === "string"){

     console.log(value.toUpperCase());

   } else {

     console.log(value.toFixed(2));

  }

}

 

- typeof 타입가드는 원시타입에 많이 사용된다.

 

in (타입 가드)

 

- 객체의 속성 존재 여부로 타입을 좁히는 방식이다.

 

type Dog  = {

   bark : () => void

};

 

type Cat = {

  meow: () => void

};

 

function makeSound(animal: Dog | Cat) {

  if ("bark" in animal) {

    animal.bark(); // Dog

  } else {

   animal.meow(); // Cat

   }

}

 

instanceof (타입 가드)

 

- 클래스 타입 좁히기

 

class Person { }

class Animal { }

 

function process(obj: Person | Animal){

  if(obj instanceof Person){

     // Person

  } else {

     // Animal 

  }

}

728x90
Comments