Interface vs Type

이대현·2023년 5월 30일
0

Typescript

목록 보기
4/6

TypeScript에서 interfacetype은 둘 다 타입 정의를 할 수 있는 기능을 제공합니다. 두 개의 기능은 비슷한 목적을 가지고 있지만 약간의 차이가 있습니다.

interface는 주로 객체의 구조를 정의하는 데 사용됩니다. 객체의 속성, 메서드, 인덱서 등을 정의할 수 있습니다. interface는 상속이 가능하며, 여러 개의 interface를 합치는 것도 가능합니다. 예를 들어:

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

interface Employee extends Person {
  employeeId: string;
}

const employee: Employee = {
  name: 'John',
  age: 30,
  employeeId: '12345'
};

type은 객체 뿐만 아니라 다른 타입들에 대한 별칭(alias)을 정의하는 데 사용됩니다. 기존의 타입을 재사용하거나 복잡한 유니온(union) 또는 인터섹션(intersection) 타입을 정의하는 데 유용합니다. 예를 들어:

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

type Color = 'red' | 'green' | 'blue';

type Person = {
  name: string;
  age: number;
};

type Employee = Person & {
  employeeId: string;
};

const employee: Employee = {
  name: 'John',
  age: 30,
  employeeId: '12345'
};

interfacetype의 가장 큰 차이점은 선언 방식과 몇 가지 세부적인 기능입니다. 예를 들어, interface는 선언 병합(declaration merging)이 가능하고, type은 타입 내에서 유니온과 인터섹션을 조합하여 새로운 타입을 만들 수 있습니다. 하지만 대부분의 경우에는 interfacetype을 상황에 맞게 사용하는 것이 좋습니다.

profile
Frontend Developer

0개의 댓글