Recent Posts
Recent Comments
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Today
Total
관리 메뉴

DH의 개발 공부로그

[TypeScript] 타입스크립트 인터페이스 - Interface 본문

TypeScript

[TypeScript] 타입스크립트 인터페이스 - Interface

DeveloperDH 2023. 2. 10. 22:07
728x90

인터페이스(interface)

인터페이스는 객체 형태를 설명해주는 설계도라고 할 수 있습니다.
type과 비슷하기도 하지만 다른점을 가지고 있고, 프로퍼티와 메소드를 가질 수 있다는 점은
클래스와 유사하기도 합니다.
인터페이스는 보통 다음과 같은 것들의 타입에 대한 약속을 정의해 줍니다.

  1. 객체의 스펙(속성과 속성의 타입)
  2. 함수의 파라미터
  3. 함수의 스펙(파라미터, 반환 타입 등)
  4. 배열과 객체를 접근하는 방식
  5. 클래스 

인터페이스와 타입의 차이점

인터페이스와 타입은 위에서 말했다 싶이 비슷합니다.
둘다 타입을 정의를 해줄 때 사용을 하고, 비슷한 역활을 하고 있기 때문 입니다.
그렇다면 차이점이 무엇인지 알아보겠습니다.

Interface는 객체의 형태만 가능하다

type UserName = string
type UserInfo = {
  name: UserName;
  age: number;
}

interface InterfaceUser {
  name: UserName;
  age: number;
  hobby: string;
}

Computed Property Name

타입은 특정한 값을 가지도록 할 수 있고, Computed Property Name방식의 문법도 사용이 가능합니다.
하지만 인터페이스는 불가능하며, 특정한 값을 가지는 것도 불가합니다.

type UserColor = 'red' | 'green' | 'blue'; // 특정한 값들을 지정 해주는 것도 가능

type ColorPalette = {
  [key in UserColor]: string;
}

const user: ColorPalette = { red: '#f00', green: '#0f0', blue: '#00f' };

interface ColorInterface {
  [key in UserColor]: string; // error
}
📌 Computed Property Name이란?
표현식(expression)을 이용해 객체의 key 값을 정의하는 ES6 문법입니다.
다음번에 다시 한번 따로 정리하도록 하겠습니다:)

확장

인터페이스는 상속의 개념을 사용할 수 있습니다. 이러한 상속은 클래스와 유사합니다.

interface InterfaceUser {
  readonly name: UserName;
  color: UserColor;
  hobby: string;
}

interface UserHealth extends InterfaceUser {
}

const son: UserHealth = {
  name: 'son';
  color: 'blue';
  hobby: 'soccer;
}
// type으로 같은 작업 만들기
type InterfaceUser1 = {
  name: UserName;
  color: UserColor;
  hobby: string;
}

type UserHealth1 = InterfaceUser1 & {
}

const son1: UserHealth1 = {
  name: 'son';
  color: 'blue';
  hobby: 'soccer';
}

선언적 확장

인터페이스에서 할 수 있는 대부분의 기능들은 타입에서 가능합니다.
하지만 타입에서는 새로운 속성을 추가해주기 위해서 다시 같은 이름으로 선언할 수 없지만,
인터페이스는 항상 선언적 확장이 가능하다는 것입니다.
속성(Property)들을 ‘축적’시킬 수 있다 특징을 가지고 있습니다.

interface Info {
  name: string;
}

interface Info {
  age: number;
}

const dier: Info = {
  name: 'dier';
  age: 20;
}
type Info = {
  name: string;
}

type Info = {
  age: number;
}
// error

Interface 클래스에서 사용하기

추상클래스의 문제점은 JavaScript에는 abstract의 개념이 없다는 것이 있습니다.
따라서 추상 클래스는 js파일로 변환이 되면 추상클래스가 아닌 일반 클래스로 변환이 됩니다.
그러나 인터페이스는 변환 될 때 바뀌지 않고 사라지기때문에 가볍다라는 특징이 있습니다.

interface Human {
  firstName: string;
  lastName: string;
  sayHi(name: string): string;
  fullName(): string;
}

interface Age {
  age: number;
}

// 📌 implements
// 인터페이스를 클래스에 상속 할 때 사용
// 또한 여러 인터페이스를 상속 받을 수도 있다.

class character implements Human, Age {
  constructor(
    public firstName: string;
    public lastName: string;
    public age: number;
  ) { }
  sayHi(name: string) {
    return 'hello';
  }
  fullName() {
    return this.firstName + this.lastName;
  }
}

결론

클래스나 객체의 모양을 정의하고 싶으면 인터페이스를 사용을 하며,
그 외의 나머지 상황에서는 타입으로 정의를 하는 것을 추천합니다.

참고

TypeScript - Interface | PoiemaWeb
인터페이스 | 타입스크립트 핸드북
typescript - 인터페이스 (interface) - 기억보다 기록을
타입스크립트 type과 interface의 공통점과 차이점 - yceffort

728x90
Comments