[TypeScript] type과 interface 차이점과 사용 팁
BE/TypeScript 2023. 6. 13.
공통점과 차이점
먼저 다음과 같은 type과 interface가 있다고 가정하자.
// type
type UserType = {
name: string;
age: number
};
// interface
interface UserInterface {
name: string;
age: number;
}
둘 다 자신을 따르는 객체와 클래스를 만들 수 있다.
예시는 다음과 같다.(객체)
const user1: UserType = {name: "John", age: 25};
const user2: UserInterface = {name: "Jane", age: 30};
확장성(Extendibility)
interface는 다른 interface를 확장할 수 있다. type은 불가능하다.
interface UserInterface {
name: string;
age: number;
}
interface AdminUser extends UserInterface {
admin: boolean;
}
type은 intersection(교차 타입)을 통해서 가능하다.
type UserType = {
name: string;
age: number;
};
type Admin = {
admin: boolean;
};
type AdminUser = UserType & Admin;
Only Interface - 재정의 및 결합
interface는 동일한 이름의 interface를 재정의 하면 결합이 된다.
interface UserImpl {
name: string;
age: number;
};
interface UserImpl {
isAdmin: boolean;
};
Interface의 정의 및 개념
Interface는 규격사항 이다. 누군가가 구현할 것이 있다면 interface를 사용하는 것이 좋다.
interface로 객체의 형태를 정의하여, 객체와 객체가 소통할 수 있게한다.
Only Type - Computed properties 사용 가능
타입은 유니온, 튜플 등 다양한 타입을 선언할 수 있다.
type StringOrNumber = string | number;
type UnionType = 'up' | 'down';
type UserTuple = [string, number];
'BE > TypeScript' 카테고리의 다른 글
[OnlyForMe] TSConfig 셋업(프로젝트 구조 정리하기) (0) | 2023.06.13 |
---|---|
[TypeScript] 다양한 Utility Type이해하기 (0) | 2023.06.13 |
[OnlyForMe] 기본 TS 프로젝트 설정하는 방법 (0) | 2023.06.12 |
[TypeScript] abstract(추상 클래스)에 대해 이해하기 (0) | 2023.06.11 |
[TypeScript] 함수와 메소드에 type alias를 붙이는 방법 (0) | 2023.06.06 |