250x250
Notice
Recent Posts
Recent Comments
관리 메뉴

탁월함은 어떻게 나오는가?

[TypeScript] 타입스크립트 type alias 과 interface 에 대해서 비교해보자 본문

[Snow-ball]프로그래밍(컴퓨터)/타입스크립트(TypeScript)

[TypeScript] 타입스크립트 type alias 과 interface 에 대해서 비교해보자

Snow-ball 2023. 4. 29. 15:09
반응형

타입스크립트를 사용하면서 꾸준하게 type alias 와 interface의 차이점이 궁금했다. 사용해보는 모든 사람들도 똑같이 느낄테지만 사용하면 사용할수록 서로가 서로의 기능이 가능하다는것을 느껴보았을 것이다.

 

그래서 이 기회에 한번 정리해서 차이점과 어떤 경우에 무엇을 사용해야 할지에 대한 주관적인 생각을 정리해볼 필요성을 느꼈다.

 

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

interface
 Animal {
    name: string;
}
 
interface Bear extends Animal {
    honey: boolean;
}
 
const bear: Bear = {
    honey: true,
    name'Foo',
};
 
type Animal2 = {
    name: string;
};
 
type Bear2 = Animal2 & {
    honey: boolean;
};
 
const bear2: Bear2 = {
    honey: true,
    name'Foo2',
};
cs

 

위의 예제를 보면 알 수 있듯이 Type Alias와 interface 모두 객체의 타입을 지정해줄 수 있다.

 

 

 


 

 

 

확장하는 방법

 

1. 기본 확장

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
interface InterfacePerson {
    name: string;
}
 
interface InterfaceStudent extends InterfacePerson {
    school: string;
}
 
const InterfaceVariable: InterfaceStudent = {
    name'interfacePerson',
    school: 'interfaceSchool',
};
 
type TypePerson = {
    name: string;
};
 
type TypeStudent = TypePerson & {
    school: string;
};
 
const TypeVariable: TypeStudent = {
    name'typePerson',
    school: 'typeSchool',
};
cs

 

2. 선언적 확장

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
interface InterfaceStudent {
    name: string;
}
 
interface InterfaceStudent {
    school: string;
}
 
const InterfaceVariable: InterfaceStudent = {
    name'interfacePerson',
    school: 'interfaceSchool',
};
 
 
// TS2300: Duplicate identifier 'TypeStudent'.
type TypeStudent = {
    name: string;
};
 
type TypeStudent = {
    school: string;
};
 
const TypeVariable: TypeStudent = {
    name'typePerson',
    school: 'typeSchool',
};
cs

 

interface의 경우에는 선언 후 같은 이름을 선언해서 추가할 수 있다.

type alias의 경우에는 생성한 이후에는 변경할 수가 없다.

 

 

 


 

 

 

원시(primitive) 타입을 할당하는것은 type만 가능하다.

 

1
2
3
4
5
6
7
8
9
// 모두 오류가 발생한다.
interface Str implements string;
interface Str2 extends string;
interface Str3 = string;
interface Str4: string;
 
// 정상 동작
type Str = string;
const stringVariable: Str = 'string';
cs

 

 

 

 


 

 

 

Property Key 설정 방법은 type 으로만 가능하다. 

1
2
3
4
5
6
7
8
9
10
11
12
type names = 'firstName' | 'lastName';
 
type TypeName = {
    [key in names]: string;
};
 
const ljh: TypeName = { firstName: 'Lee', lastName: 'JungHyun' };
 
interface InterfaceName {
    // TS7061: A mapped type may not declare properties or methods.
    [key in names]: string;
}
cs

 

 

 


 

 

 

MS github 에서는 Type Alias 의 & 보다는 Interface 를 선호한다. 

(위의 깃헙으로 들어가서 제목이 Preferring Interfaces Over Intersections 를 검색하면 본문을 확인할 수 있다)

 

1) 인터페이스는 속성 충돌을 해결하기 위해 같은 네이밍으로 선언해도 단일 객체 유형으로 만든다.

하지만 Type Alias 같은 네이밍으로 만들면 에러를 발생시키며 생성하지 않는다. 그리고 &를 사용해서 합병할 때는 재귀적으로 병합을 한다.

1
2
3
4
5
6
7
8
9
10
11
12
interface InterfaceStudent {
    name: string;
}
 
interface InterfaceStudent {
    school: string;
}
 
const InterfaceVariable: InterfaceStudent = {
    name'interfacePerson',
    school: 'interfaceSchool',
};
cs

 

 

2) Type Alias의 &는 확장을 해서 사용하면 일부에 표시할 수 없는데, 인터페이스는 일관되게 잘 표시된다.

&의 경우 확장 후 마우스를 가져다 되면 밑에 처럼 표시가 된다.

 

Interface의 확장 후 마우스를 가져다 되면 밑에 처럼 표시가 된다.

 

 

3) interface는 &와 달리 타입 관계도 캐시된다.

 

 

4) 마지막으로 & 타입과 다른 중요한 차이점은 "effective"/"flattened" 타입인지 만들어지기 전에 모두 검사를 한다.

 

 

 


 

 

 

결론

결론적으로는, Type Alias 와 Interface 의 차이점은 있지만, 크게 차이나는 점이 없다.

타입스크립트의 핸드북, 깃허브, 직접 테스트 하면서 든 생각은 Type Alias로 할 수 있는 기능을 제외하고는 Interface를 사용하는것이 적절하다는 생각이 들었다.

 

타입스크립트의 핸드북의 내용중 일부를 인용하자면 "대부분의 경우 개인 선호도에 따라 선택할 수 있으며, 다른 종류의 선언이 필요하면 타입스크립트가 알려준다. 관습적(경험적)인 방법으로 Interface를 사용하다가 Type Alia를 사용이 필요할 때 사용해라"

 

 

 

reference

* Everyday Types - Typescript

* Preferring Interfaces Over Intersections - github.com/microsoft/Typescript 

 

 

 

 

반응형
Comments