<TS> 타입 좁히기 (Narrowing)

·2023년 8월 26일
0

TypeScript

목록 보기
5/8
post-thumbnail

타입 좁히기

Typeof guards

typeof guards

typeof를 이용하여 타입을 좁힐 수 있습니다.
주로 명확하지 않은 타입이 있을 때 사용합니다.
(예로 유니온 타입이 있음)

이것을 보다 명확하게 타입을 좁힙니다.

function triple(value: number | string) {
  if (typeof value === "string") {
    return value.repeat(3);
  }
}

만약, typeof guard 방식을 사용하지 않고 코드를 아래와 같이 작성하게되면

function triple(value: number | string) {
    return value.repeat(3);
}

.repeat() 메서드는 string 타입을 반환하는 메서드입니다.
그러나 value에는 number가 들어올지 string이 들어올지 모르는 상황이기 때문에 타입 에러가 발생할 수 있습니다.

Truthiness Guards

null, undefined, falsy값을 좁히거나 제거할 수 있습니다.

const printDoc = (word: string | null) => {
  if (!word) {
    console.log("작성하신 단어가 없습니다.");
  } else {
    sentence.forEach((eachSentence) => console.log(eachSentence));
  }
};

in

대부분 인터페이스나 객체로 작업하기 때문에 typeof에서는 사용할 수 없는 예시이다.

interface Moive {
  title: string;
  duration: number;
}

interface TVShow {
  title: string;
  numEpisodes: number;
  episodeDuration: number;
}

function getRuntime(media: Moive | TVShow) {
  // 객체 key값이 포함되어 있는지 유무 체크
  if ("numEpisodes" in media) {
    return media.numEpisodes * media.episodeDuration;
  }
  return media.duration;
}

getRuntime({ title: "이터널 션샤인", duration: 120 });
getRuntime({ title: "디지몬 어드벤처", numEpisodes: 30, episodeDuration: 30 });

Type Predicates 타입 명제

간단한 명제를 통해 타입을 좁히는 방법입니다.

interface Cat {
  name: string;
  numLives: number;
}

interface Dog {
  name: string;
  breed: string;
}

function isCat(animal: Cat | Dog): animal is Cat {
  return (animal as Cat).numLives !== undefined;
}

function makeNoise(animal: Cat | Dog): string {
  if (isCat(animal)) {
    animal;
    return "애오오옹";
  } else {
    animal;
    return "멍뭥";
  }
}
profile
- 배움에는 끝이 없다.

0개의 댓글