-
타입스크립트 Type Aliases & Interfaces 알아보기TypeScript 2023. 5. 9. 22:59
타입스크립트에서 타입을 선언하는데 크게 두 가지 방법이 있다.
Type Aliases와 Interfaces에 대해서 정리하고, 각각 어느 상황에서 사용하는 것이 best case일지도 생각해보았다.
Type
type 키워드는 타입을 정의하기 위해서 모든 유형에 사용될 수 있다.
동일한 유형이 두 번이상 반복된다면, type을 선언하여 사용할 수 있다.
type 키워드는 다음과 같은 특징을 지닌다.
- 객체를 포함한 모든 유형에 대한 타입을 표현할 수 있다.
- 문자열이나 숫자 등 값을 type에 할당할 수도 있다.
type Name = string | undefined; let myName: Name; myName = "John"; type User = { nickname: string; level: number; } const john: User = { nickname: "king_john", level: 15, } /////////////////////// type Introduce = "Hello World"; const start: Introduce = "Hello World"; type Pie = 3.14 | "3.14"; const pieNumber: Pie = 3.14; type Protein = "meat" | "bean" | "beaf";- type은 aliases, 별칭일 뿐으로 unique하지 않다.
type Nickname = string; type Name = string; let firstName: Nickname = "lee"; let lastName: Name = "hoho"; lastName = firstName;- type은 재정의될 수 없다.
type Nickname = string; type Nickname = number; // ERROR Nickname = number; // ERROR- 타입 객체는 & 키워드로 합칠 수 있다.
type A = { a: string; } type B = { b: boolean; } const obj: A & B = { a: "AA", b: false, }Interfaces
interface는 객체의 타입을 정의하기 위해서 사용될 수 있다.
타입스크립트가 객체 내부에 예상되는 속성이 존재하는지 확인할 수 있게 해준다.
interface는 객체 타입의 구조와 기능에 관심을 둔다.
interface 키워드는 다음과 같은 특징을 지닌다.
- 객체에만 사용될 수 있다.
interface User { name: string; age: number; } interface Nickname = string; // ERROR- 재정의하여 확장할 수 있다.
interface User { name: string; age: number; } interface User { balance: number; } const user: User = { name: 'lee', age: 15, balance: 12000, }- 혹은 extends 키워드를 통해서 기존의 인터페이스를 확장하여 새로이 만들 수 있다.
interface User { name: string; age: number; } interface UserWithBalance extends User { balance: number; } const user: UserWithBalance = { name: 'lee', age: 15, balance: 12000, }keyof
// type type User = { name: string; nickname: string; password: number; } type UserKeys = keyof User; const keys1: UserKeys = "name"; const keys2: UserKeys = "nickname"; const keys3: UserKeys = "password"; // interface interface Computer { cpu: string; memory: string; price: number; } type ComputerKeys = keyof Computer; const keys11: ComputerKeys = "cpu"; const keys22: ComputerKeys = "memory"; const keys33: ComputerKeys = "price";type과 interface 모두에서 사용할 수 있는 키워드로, 객체에서 key들의 값을 타입으로 갖는 type을 생성할 수 있다.
🍌 type과 interface는 유사하며, 대부분의 경우 자유롭게 선택할 수 있지만 차이점은 분명히 존재한다.
interface의 거의 모든 기능은 type에서 사용될 수 있다.
interface는 새로운 속성의 확장에 열려있지만, type은 상대적으로 그렇지 않다. (다만, & 키워드로 확장이 가능하다)
다른 언어와 같이 interface는 class의 명세를 나타내기에 적합하다.
🥖 타입스크립트 공식 문서에서는 초보자에게 interface의 사용을 권장하고있다.
🍅 하지만, type aliases는 프로퍼티에 접근할 수 있고, union같은 기능을 사용할 수 있으므로 변수를 표현하기에 더 적합한 것은 type이다.
타입스크립트 공식 문서 핸드북
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases
Documentation - Everyday Types
The language primitives.
www.typescriptlang.org
참고 자료
https://stackoverflow.com/questions/72598769/intersection-types-vs-interfaces-in-typescript
Intersection types vs interfaces in typescript
Here's the scenario: type Admin = { name : string, privileges : string[] } type Employee ={ name : string, startDate : Date } type ElevatedEmployee = Admin & Employee; const e...
stackoverflow.com
https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections
Performance
TypeScript is a superset of JavaScript that compiles to clean JavaScript output. - microsoft/TypeScript
github.com
'TypeScript' 카테고리의 다른 글
typescript에서의 class (0) 2023.06.06 TypeScript의 enum에 대해서 (0) 2023.05.19 타입스크립트 에러 해결 (단항 더하기 연산자) : The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362) (0) 2023.04.04 typescript Record 타입 사용하기 (1) 2023.03.29 Typescript Generics와 Keyof, Mapped Types 사용해보기 (1) 2023.03.10