개발일지

[TS] 10. 타입스크립트의 핵심 #1 - Type과 Interface 본문

JS, TS/[TS | 강의] TS·OOP

[TS] 10. 타입스크립트의 핵심 #1 - Type과 Interface

lyjin 2022. 11. 8.

22.09.19 월

Type Alias와 Interface:

Type vs Interface (기술 측면)

type PositionType = {
  x: number;
  y: number;
};

interface PositionInterface {
  x: number;
  y: number;
}

 

 

1. object (type) : 둘 다 가능

// object ★
const obj1: PositionType = {
  x: 1,
  y: 1,
};
const obj2: PositionInterface = {
  x: 1,
  y: 1,
  z: 1,
};

 

2. class (implements) : 둘 다 가능

 

// class ★
class Pos1 implements PositionType {
  x: number;
  y: number;
}
class Pos2 implements PositionInterface {
  x: number;
  y: number;
}

 

3. extends : 둘 다 가능

 

interface ZPositionInterface extends PositionInterface {
  z: number;
}
type ZPositionType = PositionType & { z: number };

 

 

4. merge : interface만 가능

interface PositionInterface {
  z: number;
}
// 위의 PositionInterface와 merge되어 x,y,z를 갖게 됨

type PositionType {  //type은 중복 불가
}

 

5. computed properties : type만 가능

 

type Person = {
  name: string;
  age: number;
};
type Name = Person['name']; // string 타입

type NumberType = number;
type Direction = 'left' | 'right';
 


Type vs Interface (개념 측면)

  • interface
    • 규약 정의할 때 사용
  • type
    • 데이터에 대한 type 나타내고 싶을 때 사용
// 예시)

type Position = {
  x: number;
  y: number;
};

const pos: Position = { x: 0, y: 0 };