[TIL] TS as, is란

Demian·2024년 2월 12일
0

1. as

TS에서 as는 타입 단언에 쓰인다.
TS 컴파일러는 타입 표기, 타입 좁히기와 타입 추론 등의 기법을 이용해 값의 타입을 판단한다. 하지만 때로는 컴파일러가 가진 정보를 무시하고 프로그래머가 원하는 임의의 타입을 값에 할당하고 싶을 수 있다. 이럴때 필요한 것이 바로 타입 단언(type assertion)이다.

타입 단언 문법

interface Dog {
  legs: 4;
  bark(): void;
}

interface Insect {
  legs: number;
  creepy: boolean;
}

interface Fish {
  swim(): void;
}

type Animal = Dog | Insect | Fish;

function doSomethingWithAnimal(animal: Animal) {
  (animal as Fish).swim();
}

위의 코드는 Animal 타입의 값을 Fish로 단언한다.
주의할 점은 타입 단언은 타입 에러를 없애줄 뿐 런타임 에러를 막아주지 않는다는 점이다. 오히려 그 반대인데, 컴파일 타입에 잡을 수 있는 에러를 없앰으로서 원래대로면 생기지 않았을 런타임 에러를 발생시킬 수 있다. 위 함수는 런타임에 Dog 혹은 Insect 타입 값을 받으면 터질 것이다.

2. is

TS에서 is는 사용자 정의 타입 가드' value is Type 형태'의 반환 타입을 갖는 함수에서 사용된다.

function isFish(animal: Animal): animal is Fish {
  if ('legs' in animal) {
    return false;
  }
  return true;
}

function doSomethingWithAnimal(animal: Animal) {
  if (isFish(animal)) {
    // animal은 Fish 타입
    animal.swim();
  } else {
    // animal은 Dog | Insect 타입
    console.log(animal.legs);
  }
}

타입 단언은 컴파일단계에서 오류를 잡아낼 수 없기 때문에 타입 단언(as Type)보다는 타입가드를 잘 활용해서 타입 선언(:Type)을 지향하자.

참조

https://ahnheejong.gitbook.io/ts-for-jsdev/06-type-system-deepdive/type-assertion ts-for-jsdev

0개의 댓글