728x90
728x90

인터페이스(Interface)와 타입 별칭(Type Alias) 비교

들어가며

  • 인터페이스(Interface)와 타입 별칭(Type Alias)은 타입스크립트에서 타입을 정의하는 방법이다.
  • 타입스크립트(TypeScript)에서 인터페이스(Interface) 타입 별칭(Type Alias)의 차이에 대해 정리해본다.

 

인터페이스(Interface)

개념

  • 인터페이스는 주로 객체(Object)의 구조를 정의하는 데 사용된다.
  • 주로 객체의 속성과 메서드를 정의하는 데 사용된다.
  • 인터페이스를 구현하는 객체는 해당 인터페이스에서 요구하는 속성이나 메서드반드시 포함해야 한다.
  • 코드에서 객체의 구조를 명확하게 정의하고, 다른 코드에서 해당 구조를 따르도록 강제할 때 유용하다.
  • interface 키워드를 이용하여 생성할 수 있다.
interface Person {
name: string;
age: number;
}

 

특징

  • 인터페이스는 선언 병합(Declaration Merging)을 통해 같은 이름의 인터페이스가 여러 번 선언될 때 자동으로 병합된다.
  • 인터페이스는 주로 객체의 구조를 정의하는 데 사용되며, 클래스(Class)와 함께 사용하여 클래스가 인터페이스의 구조를 따르도록 할 수 있다.
  • 클래스는 인터페이스를 구현(implements) 할 수 있으며, 인터페이스에 정의된 모든 속성과 메서드를 클래스에서 반드시 구현해야 한다.

 

기능

선언 병합(Declaration Merging)

  • 인터페이스는 같은 이름으로 여러 번 정의하면 타입스크립트가 자동으로 병합(Merge)하여 모든 정의를 포함하단일 인터페이스를 만든다.
interface Person {
name: string;
}
interface Person {
age: number;
}
// 최종 결과 : { name: string; age: number; }

 

클래스 구현

  • 인터페이스는 클래스(Class)구현(implements) 할 수 있는 일종의 계약 사항(Contract)을 제공한다.
// 인터페이스 정의
interface Person {
name: string;
age: number;
greet(): void;
}
// 클래스에서 인터페이스 구현
class Employee implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}

 

타입 별칭(Type Alias)

개념

  • 특정 타입에 이름을 부여하는 방법
  • 타입 별칭을 사용하면 다양한 타입(객체, 기본 타입, 유니언 타입, 교차 타입 등)에 이름을 붙여 코드에서 그 이름으로 해당 타입을 사용할 수 있다.
  • 코드의 재사용성을 높이고, 특정 타입을 명확하게 표현할 수 있게 해준다.
  • type 키워드를 이용하여 생성할 수 있다.
// 기본 타입 별칭
type ID = string;
type Age = number;
// 객체 타입 별칭
type Person = {
name: string;
age: number;
};
// 유니언 타입 별칭
type NumberOrString = number | string;
// 문자열 형태 별칭
type Direction = 'up' | 'down' | 'left' | 'right';

 

특징

  • 객체, 기본 타입(숫자, 문자열 등), 유니언 타입, 교차 타입 등 다양한 타입을 표현할 수 있다.
  • 같은 이름으로 여러 번 선언할 수 없으며, 새로운 속성을 추가하거나 확장할 수 없다.
  • 객체 타입뿐만 아니라, 기본 타입(Primitive Types)과 같은 단순한 타입도 별칭으로 정의할 수 있다.

 

기능

다양한 타입 표현

  • 타입 별칭은 객체(Object) 외에도 기본 타입(Primitive Types), 유니언 타입(Union Types), 교차 타입(Intersection Types), 튜플(Tuple) 등 여러 종류의 타입을 표현할 수 있다.
type NumberOrString = number | string; // 유니언 타입
type Person = {
name: string;
age: number;
};

 

Computed Properties

  • 타입 별칭은 계산된 속성(Computed Property) 이름을 사용할 수 있다.
  • 이 기능은 인터페이스(Interface)에서는 지원되지 않는다.
const propName = 'age';
type Animal = {
[propName]: number; // computed property
};
let tiger: Animal = { [propName]: 5 };

 

병합 불가

  • 타입 별칭은 선언 병합(Declaration Merging)불가능하다.
    • 같은 이름의 타입을 여러 번 선언하면 에러가 발생한다.
// 첫 번째 타입 별칭
type Person = {
name: string;
};
// 두 번째 타입 별칭 (동일한 이름 사용)
type Person = {
age: number;
};
// 오류 발생

 

요약

  • 인터페이스와 타입 별칭의 주요 차이점을 요약해보면 아래와 같다.
특징 타입 별칭(Type Alias) 인터페이스(Interface)
기본 타입 정의 가능
(number, string, union 타입 등)
불가능
(객체 구조만 정의 가능)
계산된 속성
(Computed Property)
가능 불가능
선언 병합
(Declaration Merging)
불가능 가능
클래스 구현
(Class Implementation)
불가능 가능
사용 용도 여러 타입을 표현할 때
(객체, 유니언, 튜플 등)
객체의 구조를 정의할 때

 

참고 사이트

 

W3Schools.com

TypeScript allows types to be defined separately from the variables that use them. Aliases and Interfaces allows types to be easily shared between different variables/objects.

www.w3schools.com

 

Documentation - Declaration Reference

How to create a d.ts file for a module

www.typescriptlang.org

 

728x90
728x90

인터페이스(Interface)와 타입 별칭(Type Alias) 비교들어가며인터페이스(Interface)개념특징기능선언 병합(Declaration Merging)클래스 구현타입 별칭(Type Alias)개념특징기능다양한 타입 표현Computed Properties병합 불가요약참고 사이트