티스토리 뷰

TypeScript

[TypeScript] interface vs. type

ljy98 2022. 6. 14. 17:36

1. interface와 type 유사성

2. interface와 type 차이점


 

[그림 1] type과 interface

TypeScript에서 타입을 정의하는 방식은 2가지가 있다. 바로 interface와 type이다.

이 글에서는 두 방식의 유사성과 차이점에 대해 알아보고자 한다.

 

 

1. interface와 type 유사성

1.1. interface와 type 선언 방식

/* interface */

interface Person {
    name: string
    age: number
}

const jiyoung: Person = {
    name: "jenny",
    age: 25,
}

/* type */

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

const jiyoung: Person = {
    name: "jenny",
    age: 25,
}

interface와 type의 선언 방식은 유사하다.

 

1.2. 확장(상속) 방법

interface Person {
    name: string
    age: number
}

interface Student extends Person {
    University: string
}

type Person = {
    name: string
    age: number
}

type Student = Person & {
    University: string
}

interface는 extends 키워드를 통해 확장이 되고, type alias의 경우 & (intersection type)를 이용한다.

 

 

2. interface와 type 차이점

2.1. 선언적 확장 (Declaration Merging) / 자동 확장

interface Animal {
    weight: number
}

interface Animal {
    height: number
}

const tiger: Animal = {
    weight: 100,
    height: 200,
}

type _Animal = {
    weight: number
}

type _Animal = {
    height: string
}

interface는 새로운 속성을 추가하기 위해서 다시 같은 이름으로 선언하여 확장이 가능하지만, type은 불가능하다.

 

위의 코드의 경우 interface로 선언한 Animal은 weight과 height 속성을 갖게 되지만, type으로 선언한 _Animal의 경우 height을 선언하는 과정에서 중복으로 선언했다는 에러가 발생한다.

 

2.2. interface는 객체만 가능

interface AnimalInterface {
    name: string
}

type AnimalType = {
    name: string
}

type AnimalOnlyString = string
type AnimalTypeNumber = number

interface X extends string {} // 불가능

type은 여러 타입으로 선언이 가능하지만, interface는 객체에만 사용이 한정된다.

 

2.3. computed value 사용

type names = 'firstName' | 'lastName'

type NameTypes = {
    [key in names]: string
}

const jy: NameTypes = { firstName: 'hi', lastName: 'jy' }

interface NameInterface {
    [key in names]: string // error
}

type은 computed value의 사용이 가능하지만, interface는 불가능하다.

 

 

Q. type과 interface 중에서 어떤 것을 쓰는 것이 좋은가?

TypeScript 공식 문서에서는 interface의 사용을 추천하고 있다. 하지만 interface는 객체 타입을 생성하므로 유니온(|) 타입이나 튜플, 단순한 리터럴 타입 선언의 경우 type을 사용하면 된다.

 

// 문자열 리터럴로 타입 지정
type Str = 'Lee';

// 유니온 타입으로 타입 지정
type Union = string | null;

// 문자열 유니온 타입으로 타입 지정
type Name = 'Lee' | 'Kim';

// 숫자 리터럴 유니온 타입으로 타입 지정
type Num = 1 | 2 | 3 | 4 | 5;

// 객체 리터럴 유니온 타입으로 타입 지정
type Obj = {a: 1} | {b: 2};

// 함수 유니온 타입으로 타입 지정
type Func = (() => string) | (() => void);

// 인터페이스 유니온 타입으로 타입 지정
type Shape = Square | Rectangle | Circle;

// 튜플로 타입 지정
type Tuple = [string, boolean];
const t: Tuple = ['', '']; // Error

type을 사용하는 경우 위의 예시를 참고하면 된다.

'TypeScript' 카테고리의 다른 글

[TypeScript] P2P(peer-to-peer) 구현  (0) 2022.06.17
[TypeScript] Block Chain 구조  (0) 2022.06.16
TypeScript 개발 환경 설정 (ESLint, Prettier)  (0) 2022.06.10
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/09   »
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
글 보관함