타입스크립트 Type Guard (타입 가드)

hellow_coding·2023년 5월 23일

Type Guard

: 타입스크립트 Type Guard 및 타입을 좁혀나가는 방법으로, 컴파일러가 타입을 예측할 수 있도록 타입을 좁혀 주어서 좀 더 type safety함을 보장할 수 있습니다.


1. typeof

피연산자의 타입을 판단하여 문자열로 반환해 줍니다.

function testFunc(arg: string | number) {
  arg.substring(3); // Error

  if (typeof arg === "string") {
    // 여기 밑에서 사용하는 arg는 반드시 string type으로 인식합니다.
    arg.substring(3);
  }
}

조건문 블록 내에서 타입을 인식하여 (조건)type임을 보장하게 합니다.


2. instanceof

판별할 객체가 특정한 클래스에 속하는지 확인할 수 있습니다.

class Student {
  name: string;
  age: number;
}
class School {
  location: string;
}

function testFunc(arg: Student | School) {
  if (arg instanceof Student) {
    console.log(arg.name); // OK
    console.log(arg.location); // Error
  } else {
    // 여기서부터는 arg가 반드시 School 타입으로 인식합니다.
    console.log(arg.location); // OK
  }
}
testFunc(new Student());
testFunc(new School());

3. 사용자 지정 Type Guards

사용자 정의 Type Guard 함수란 단순히 어떤 인자명은 어떠한 타입이다라는 값을 리턴하는 함수일 뿐입니다.

interface ZeroBody {
  age: 0; // 반드시 0만 가능하다는 의미
  name: string;
}

interface OtherBody {
  age: number;
  name: string;
}

interface Response {
  type: string;
  body: ZeroBody | OtherBody;
}

function isZero(arg: any): arg is ZeroBody {
  return arg.age === 0;
  // return arg.age !== undefined;
}

function doSomething(arg: Response) {
  const { type, body } = arg;

  if (ZeroBody(body)) {
    // 이 if문 안에서 body의 타입은 반드시 ZeroBody 인터페이스이다.
    console.log(body.age); // 0
  } else {
    // 이 if문 안에서 body의 타입은 반드시 OtherBody 인터페이스이다.
    console.log(body.age);
  }
}

Array

1. Araays.isArray

배열인지 아닌지를 판별하는 JavaScript의 내장 함수입니다.

console.log(Array.isArray([1, 2, 3]));  // true
console.log(Array.isArray({foo: 123})); // false
console.log(Array.isArray('Hello'));   // false
console.log(Array.isArray(undefined)); // false
profile
꿈많은 개발자

0개의 댓글