[스터디] 타입스크립트 개념 알아보기 3 (리터럴, 유니온, 교차)

나리·2024년 8월 16일

1. 리터럴 타입 (Literal type)

리터럴 타입은 특정값 자체를 타입으로 사용하는 것이다.
값 그 자체를 타입으로 지정을 하는 것인데, 이렇게 하면 해당 변수는 지정된 값 이외의 값을 가질 수 없다.


// const: 변하지 않는 값 / let: 변할 수 있는 값을 선언할 때 사용
// const userName1 과 같이 특정값 자체를 타입으로 사용하는 것이 Literal type
const userName1 = "Bob";
let userName2 = "Tom";

/// 

type Job = "police" | "developer" | "teacher"

interface User {
    name: string;
    job: Job;
}

const user: User = {
    name: "Bob",
    job: "student" // error: 명시된 리터럴 타입에 포함되지 않음
}

2. 유니온 타입 (Union type)

유니온 타입은 여러 타입 중 하나를 가질 수 있는 변수를 정의할 때 사용한다. 동일한 속성의 타입을 다르게 하여 구분지을 수 있으며 주로 파이프 기호 (|) 를 사용하여 표현한다.

interface Car {
    name: "car"
    color: string;
    start(): void;
}

interface Mobile {
    name: "mobile";
    color: string;
    call(): void;
}

function getGift(gift: Car | Mobile){
    console.log(gift.color);
    // error: car 에만 start가 있기 때문 
    // 따라서, car인지 부터 먼저 알아봐야 한다. 
    gift.start();

}

위와 같이 car 와 Mobile 에 모두 color 가 있기 때문에 문제가 없지만 아래 gift.start() 에서 오류가 발생한다.

이는 car 에는 start가 있지만 Mobile 에는 start가 없기 때문인데 if문을 사용하여 car 일때에는 start를, Mobile 일때에는 call 이 나오게 하면 된다.

아래가 이에 대한 코드이다.

interface Car {
  name: "car";
  color: string;
  start(): void;
}

interface Mobile {
  name: "mobile";
  color: string;
  call(): void;
}

function getGift(gift: Car | Mobile) {
  console.log(gift.color);
  if (gift.name === "car") {
    gift.start();
  } else {
    gift.call();
  }
}

3. 교차 타입 (Intersection type)

교차타입은 여러 타입을 모두 만족하는 타입을 정의하고 싶을때 사용한다. 두 타입의 모든 속성과 매소드를 동시에 가지고 있으며 주로 앰퍼샌드 기호 (&) 를 사용하여 표현한다.

interface Car {
  name: string;
  start(): void;
}

interface Mobile {
  name: string;
  color: string;
  price: number;
}

// 모든 속성을 다 기입해줘야 한다 
const mobileCar: Mobile & Car = {
    name: "아무튼짱멋진자동차", 
    start() {},
    color: "아무튼짱예쁜색깔",
    price: 1000,
};

후기:
유니온은 or / 교차는 and 의 의미인거 같다

0개의 댓글