관리 메뉴

Silver Library (Archived)

뭘 놓쳤을까? - type, interface 본문

Face the fear, build the future/Revision Sector

뭘 놓쳤을까? - type, interface

Chesed Kim 2022. 6. 4. 22:24
반응형

type 과 interface. 타입스크립트에서 쓰이는 두 선언을 기록하는 유형 정도로 인식하고 있다.

 

type 은 단일 class 같은 성격을 가졌고, 따라서 유연하게 extends 해서 연달아 애드온 하듯이 작성하는 것은 불편하다는 인식이다.

 

반면, interfcae 의 경우, 연달아 사용해서 쓰는게 가능하다는 인식이다.

 

자, 체스판을 한번 뒤집어보자.

 

이 type 의 경우, 사실 interface 와 마찬가지로 도중에 끼워넣기 식으로 추가할 수 있다.

아래의 type kimochi 에 있는 내용을, 그 다음 doredake 에서 이어 적용하듯이. 아래 두번째 doredake 를 보면 알 수 있다. 

type kimochi = {
	a: string
    b: number
}

type doredake = kimochi & {
	c: string
    d: number
}

 

반면 interface 는 react 처럼 extends 하면 끝이다.

type yaranaika 를, 아래의 interface koibito 에도 마찬가지로 적용 하고 싶다면 extends yaranaika 로 가능하다. 

type yaranaika = {
	a: string
    b: number
}

interface Koibito extends yaranaika {
	name: string
    age?: number
}

 

추가:

여담이지만, Object type (객체 유형) 은 아래와 같이 사용 가능하다.

// The parameter's type annotation is an object type
function hayaku(yume: { x: number; y: number }) {
  console.log("Kimino tanjoubi wa " + yume.x);
  console.log("Kimino sukina hi wa " + yume.y);
}
hayaku({ x: 3, y: 7 });