본문 바로가기

개발에 도움이 되는/TypeScript

TypeScript 기본 (Literal, Union / Intersection Type)

- Literal Type

string, number, boolean 같은 type을 이용하여 정확한 값을 지정 가능

 

- 기본 예제

type Job = "developer" | "teacher" | "singer";

 

interface User {

  name : string;

  job : Job;

}

 

const An: User = {

  name : "An",

  job : "developer";  //  Job에 선언된 것 외에 다른 것으로 선언하면 에러

}

 

 

- Union Type

여러 type이 올 수 있는 경우에 사용하면 좋음 (or의 의미)

 

- 기본 예제

interface Food {

  name : "food";

  type : string;

  eat() : void;

}

 

interface Drink {

  name : "drink";

  type : string;

  drink() : void;

}

 

function getSomething(something: Food | Drink) {

  console.log(something.type); // 각 interface에 type이 있으므로 에러가 발생하지 않음

// if문으로 분기

  if (something.type === "food") {

    something.eat(); 

  } else {

    something.drink();

  }

// case가 많다면 switch 문을 이용

  switch (something.type) {

    case "food":

      something.eat();

      break;

    case "drink":

      something.drink();

      break;

    default:

      console.log("default");

      break;

  }

}

 

 

- Intersection Type

여러 tpye을 하나로 합치고 싶은 경우에 사용하면 좋음 (and의 의미)

 

- 기본 예제

interface Food {

  name : string;

  type : string;

  eat() : void;

}

 

interface Drink {

  name : string;

  type : string;

  drink() : void;

}

 

// Food와 Drink의 모든 속성들을 선언해야 함 

const something: Food & Drink = {

  name: "와퍼세트",

  type: "세트메뉴",

  eat() {},

  drink() {},

};

반응형