[내일배움캠프] TIL_230118

JungHoon Han·2023년 1월 18일
0

내일배움캠프

목록 보기
57/78

TS : interface 와 type 의 차이

type과 interface는 객체 타입의 이름을 지정하는 방법이다.

// interface 
interface AnimalInterface {
  species: string;
  height: number;
  weight: number;
}

const tiger: AnimalInterface = {
  species: "tiger",
  height: 200,
  weight: 300,
};

// type
type AnimalType = {
  species: string;
  height: number;
  weight: number;
};

const lion: AnimalType = {
  species: "lion",
  height: 180,
  weight: 400,
};

차이점

  • 확장하는 방법(상속)
    interfaceextends로 상속하고, type&(특수문자)으로 상속한다.

  • 선언적 확장
    type은 새로운 속성을 추가하기 위해 다시 같은 이름으로 선언할 수 없다.

    // interface
    interface Animal {
      weight: number;
    }
    
    interface Animal {
      height: number;
    }
    
    const tiger: Animal = {
      weight: 100,
      height: 200,
    };
    console.log(tiger);
    // type
    type _Animal = {
      weight: number;
    };
    
    type _Animal = {//error : 식별자가 중복됨
      height: string;
    };
  • interface는 객체(Object)에서만 사용이 가능
    interface는 리터럴 타입으로 확장할 수 없다.

    interface AnimalInterface {
      name: string
    }
    
    type AnimalType = {
      name: string
    }
    
    type AnimalOnlyString = string
    type AnimalTypeNumber = number
    
    interface X extends string {} // 불가능
  • interface는 객체지향 프로그래밍의 개념을 활용해서 디자인되었고, type은 좀 더 유연하고 개방적이다.

profile
Node.js 주니어 개발자

0개의 댓글