[typescript] 타입 가드와 타입 단언의 사용 예시

타입스크립트(TypeScript)는 정적 타입을 지원하는 자바스크립트의 확장 언어입니다. 타입 가드(Type Guard)와 타입 단언(Type Assertion)은 타입스크립트에서 유용하게 사용되는 기능입니다.

타입 가드(Type Guard)

타입 가드는 런타임에 특정 타입의 값을 확인하여 해당 타입을 가진다고 단언하는 도구입니다. 주로 사용되는 타입 가드는 typeof, instanceof, 그리고 사용자 정의 가드 함수입니다.

typeof를 사용한 예시

function printValue(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase());
  } else {
    console.log(value.toFixed(2));
  }
}

printValue("hello"); // 출력: "HELLO"
printValue(123.456); // 출력: 123.46

instanceof를 사용한 예시

class Cat {
  sleep() {
    console.log("Cat is sleeping");
  }
}

class Dog {
  bark() {
    console.log("Dog is barking");
  }
}

function petAction(animal: Cat | Dog) {
  if (animal instanceof Cat) {
    animal.sleep();
  } else {
    animal.bark();
  }
}

petAction(new Cat()); // 출력: "Cat is sleeping"
petAction(new Dog()); // 출력: "Dog is barking"

사용자 정의 가드 함수를 사용한 예시

interface Bird {
  fly(): void;
}

function isBird(animal: Bird | unknown): animal is Bird {
  return (animal as Bird).fly !== undefined;
}

function makeItFly(animal: Bird | unknown) {
  if (isBird(animal)) {
    animal.fly();
  } else {
    console.log("Not a bird");
  }
}

makeItFly({ fly: () => console.log("Bird is flying") }); // 출력: "Bird is flying"
makeItFly({ swim: () => console.log("Fish is swimming") }); // 출력: "Not a bird"

타입 단언(Type Assertion)

타입 단언은 개발자가 컴파일러에게 “나는 이 변수가 어떤 타입이라고 확신한다”고 알려주는 기능입니다.

let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;

console.log(strLength); // 출력: 16

타입 가드와 타입 단언은 타입스크립트 코드에서 다양한 상황에서 사용되어 타입 안정성을 유지하는 데 도움을 줍니다.

이러한 사용 예시들은 타입스크립트 코드를 더욱 안전하고 가독성 있게 유지하는 데 도움을 줄 것입니다.

참고 문헌: 타입 가드, 타입 단언