본문 바로가기

TypeScript

[TypeScript] type VS interface

 

type은 TypeScript에서 타입 별칭(Type Alias)을 정의할 때 사용되는 키워드로 유연성에 그 특징이 있습니다

 

둘 다 타입 체킹에 사용되며, 객체의 형태를 정의할 수 있고,  제네릭 사용 가능하다는 공통점이 있지만

역시나 각자 차이가 있습니다.

 

interface Box<T> {
    value: T;
}

type Box<T> = {
    value: T;
}

 

 

일단 interface 로 정의하면 객체의 타입을 명확하게 정의할 수 있습니다.( 객체 지향적입니다)

그리고 여러 클래스가 구현해야 하는 구조를 다수의 인터페이스로 정의할 수 있습니다.

class Person implements Aaa, Bbb {
}

(자바처럼 여러 interface를 implements 하는 게 가능합니다)

 

 

그 외 차이점은 크게 5가지를 들 수 있습니다.

이 차이점을 기준으로 기본은  interface 위주로 선택하되

필요에 따라 type 과 interface 의 사용 유무를 결정하시면 됩니다.

(하지만 팀 컨벤션이 먼저 입니다 :)  )

  interface type
선언 병합(Declaration Merging) 가능? O X
extends 가능? O X
유니온 / 인터섹션 타입 사용 가능? X O
기본 타입 선언 가능 ? X O
'Mapped Types'  적용 가능? X O

 

 

 

1. 선언 병합(Declaration Merging)

// Interface는 선언 병합 가능
interface Animal {
    name: string;
}
interface Animal {
    age: number;
}
// 결과: Animal은 name과 age 모두 가짐

// Type은 선언 병합 불가능
type Animal = {
    name: string;
}
type Animal = { // 오류 발생!
    age: number;
}

 

 

2. 유니온 / 인터섹션 타입

// Type은 유니온 타입 가능
type Status = "pending" | "completed" | "failed";

// Interface는 유니온 타입 직접 정의 불가

 

 

3. 기본 타입 선언 가능

// Type은 기본 타입  가능
type StringArray = string[];
type NumberOrString = number | string;

// Interface는 객체 형태만 가능

 

 

4. 'Mapped Types'  적용 가능

- 타입의 키를 동적으로 계산하여 타입을 생성하는 기능

// API 응답 타입을 모두 nullable하게 만들기
type Nullable<T> = {
    [K in keyof T]: T[K] | null;
}

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

type NullablePerson = Nullable<Person>;
// 결과:
// {
//    name: string | null;
//    age: number | null;
// }