하얀 코딩

[TypeScript - 8] 타입 가드(Type Guard) 본문

TypeScript

[TypeScript - 8] 타입 가드(Type Guard)

whitecoding 2023. 6. 6. 21:58

타입 가드(Type Guard)는 타입스크립트에서 특정 타입을 확인하고 

해당 타입에 대한 추가적인 동작을 수행하기 위해 사용되는 메커니즘입니다. 

 

타입 가드를 사용하면 컴파일러가 타입을 추론하고, 해당 타입에 따라 코드를 분기할 수 있게 됩니다. 

이를 통해 더욱 안정적인 코드를 작성할 수 있고, 런타임 에러를 방지할 수 있습니다.

 

타입 가드를 사용하는 방법은 여러 가지가 있습니다. 

일반적으로 typeof, instanceof, in 연산자, 사용자 정의 타입 가드 함수 등을 사용합니다.


typeof

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

instanceof

class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

class Cat extends Animal {
  meow() {
    console.log('Meow!');
  }
}

class Dog extends Animal {
  bark() {
    console.log('Woof!');
  }
}

function playWithPet(pet: Cat | Dog) {
  if (pet instanceof Cat) {
    pet.meow();
  } else {
    pet.bark();
  }
}

in

interface Circle {
  kind: 'circle';
  radius: number;
}

interface Square {
  kind: 'square';
  sideLength: number;
}

type Shape = Circle | Square;

function getArea(shape: Shape) {
  if ('radius' in shape) {
    return Math.PI * shape.radius ** 2;
  } else {
    return shape.sideLength ** 2;
  }
}