[typescript] 타입스크립트의 타입 정의 (인터페이스 | 타입 | 리터널 타입 | 유니온 타입 | 인터섹션 타입 | 열거형)

hellow_coding·2023년 8월 3일

타입스크립트에서 정의하는 타입에는 여러 가지가 있습니다.

📌 인터페이스(Interface)

: 객체의 구조를 정의하는 타입입니다. 확장이 가능합니다.
특정 객체가 인터페이스의 구조를 따르도록 강제할 수 있으며, 코드의 가독성과 재사용성을 높입니다.

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

const john: Person = { name: "John", age: 30 };

📌 타입(Type)

: 인터페이스와 유사하게 객체의 구조를 정의하는 타입입니다. 인터페이스와의 주요 차이점은 type은 객체, 유니온 타입, 튜플, 함수 등 여러 가지 형태의 타입을 정의할 수 있지만, interface는 더욱 객체에 특화되어 있습니다.

type Point = {
  x: number;
  y: number;
};

const origin: Point = { x: 0, y: 0 };

✔️인터페이스 vs 타입의 차이점🤔

1. 확장(Extends) 기능

// interface
interface Shape {
  color: string;
}

interface Circle extends Shape {
  radius: number;
}

const circle: Circle = { color: "red", radius: 5 };
// type
type ShapeType = {
  color: string;
};

type CircleType = ShapeType & {
  radius: number;
};

const circle: CircleType = { color: "red", radius: 5 };

인터페이스는 extends 키워드를 사용하여 다른 인터페이스를 확장할 수 있습니다. 반면, 타입은 인터섹션(&)을 사용하여 다른 타입과 결합하여 새로운 타입을 생성합니다.


2. 선언 합치기

// interface
interface Fruit {
  name: string;
}

interface Fruit {
  color: string;
}

const apple: Fruit = { name: "Apple", color: "red" };
// type
type Vegetable = {
  name: string;
};

type Vegetable = {
  color: string;
};

const carrot: Vegetable = { name: "Carrot", color: "orange" };  // 오류

인터페이스는 같은 이름으로 여러 번 선언될 때, 해당 이름의 인터페이스가 확장되어 합쳐집니다. 반면, 타입은 같은 이름으로 선언하면 오류가 발생합니다.




📌 리터널 타입(Literal Types)

: 리터널 타입은 특정 값을 정확히 나타내기 위해 사용되는 타입으로, 문자열, 숫자, 불리언 등의 값들을 나타낼 수 있습니다.

const myString: "Hello" = "Hello"; // 문자열 리터럴 타입
const myNumber: 42 = 42; // 숫자 리터럴 타입
const myBoolean: true = true; // 불리언 리터럴 타입

리터널 타입은 특정 값을 지정할 수 있으므로, 해당 값 외에 다른 값은 할당할 수 없습니다. 이러한 특성으로 오타를 방지하고 정확한 값을 보장할 수 있습니다.




📌 유니온 타입(Union Types)

: 유니온 타입은 여러 개의 타입 중 하나를 허용하는 타입으로, | 기호를 사용하여 정의합니다. 유니온 타입은 여러 타입의 조합을 표현하며, 해당 타입 중 하나의 값이 할당될 수 있습니다.

let myVariable: number | string; // 유니온 타입

myVariable = 42; // 유효
myVariable = "Hello"; // 유효
myVariable = true; // 에러: boolean 타입은 허용되지 않음

유니온 타입은 다양한 타입의 값들을 처리할 수 있으며, 각각의 타입을 따로 명시할 필요 없이 한 변수에서 다양한 타입을 처리할 수 있습니다.


✔️리터널 타입 vs 유니온 타입의 차이점🤔

리터널 타입은 특정 값을 정확하게 나타내기 위해 사용됩니다. 해당 값 외에 다른 값을 할당할 수 없습니다.
유니온 타입은 여러 개의 타입 중 하나를 허용하는 타입으로, 각각의 타입을 |로 연결하여 정의합니다. 다양한 타입의 값을 처리할 수 있습니다.




📌 인터섹션 타입(Intersection Types)

: 두 개 이상의 타입을 결합하여 새로운 타입을 생성합니다. 인터페이스와 타입의 속성들을 합치는 데 사용됩니다.

interface A {
  propA: number;
}

interface B {
  propB: string;
}

type CombinedType = A & B;

const obj: CombinedType = { propA: 42, propB: "Hello" };



📌 열거형(Enum)

: 특정 값에 이름을 부여하는 것으로, 숫자 또는 문자열 값의 집합을 나타냅니다.

※숫자 기반 emum 예시

enum Direction {
  Up, // 0
  Down, // 1
  Left, // 2
  Right, // 3
}

const move = (direction: Direction) => {
  if (direction === Direction.Up) {
    console.log("Moving up");
  } else if (direction === Direction.Down) {
    console.log("Moving down");
  } else if (direction === Direction.Left) {
    console.log("Moving left");
  } else if (direction === Direction.Right) {
    console.log("Moving right");
  } else {
    console.log("Invalid direction");
  }
};

move(Direction.Up); // 출력: "Moving up"
move(Direction.Right); // 출력: "Moving right"
move(2); // 출력: "Moving left" (숫자 기반 enum은 역참조도 가능합니다)

숫자 기반 enum에서는 역참조(reverse mapping)가 지원되기 때문에 숫자 값을 사용하여 enum 멤버를 참조할 수 있습니다.


※문자열 기반 enum 예시

enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}

const setColor = (color: Color) => {
  if (color === Color.Red) {
    console.log("Set color to red");
  } else if (color === Color.Green) {
    console.log("Set color to green");
  } else if (color === Color.Blue) {
    console.log("Set color to blue");
  } else {
    console.log("Invalid color");
  }
}

setColor(Color.Red); // 출력: "Set color to red"
setColor("GREEN"); // 출력: "Set color to green" (문자열 기반 enum도 역참조 가능)

문자열 기반 enum은 각 멤버에 문자열 값을 직접 할당합니다.

profile
꿈많은 개발자

1개의 댓글

comment-user-thumbnail
2023년 8월 3일

개발자로서 성장하는 데 큰 도움이 된 글이었습니다. 감사합니다.

답글 달기