HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🐣
프론트엔드 데브코스 4기 교육생
/
💯
김동영2팀
/
🆒
Space Club 프로젝트
/
💻
개발 규칙
/단일 타입 경우 type, 객체의 경우 interface/
[TS] type과 interface의 차이

[TS] type과 interface의 차이

type, interface 차이 ?

배경: as키워드로 타입 단언을 하려할 때, interface로 하면 에러가 발생했다. 평소, type과 interface의 차이를 모른채 사용하고 있었는데 이 기회에 차이점을 정리한다.
  • type
    • 어떤 데이터의 형식이 담길지 정의하는 것
    • 상자에 어떤 스티커를 붙일지 생각해보자. 여기서 스티커가 그 type!
    • 확장 가능함
    • type order = { menu: string, quantity: number, } type DetailOrder = order & { Requirements: string }
  • interface
    • 소통할 때 필요한 규격사항 정의한 것
    • 인터페이스로 클래스 다형성을 구현할 수 있다.
    • type CoffeeCup = { shots: number; hasMilk?: boolean; hasSugar?: boolean; }; // interface로 필수규격을 정의해서, 다양한 커피기계를 만들 수 있다. interface CoffeeMaker { makeCoffee(shots: number): CoffeeCup; } class americanoMachine implements CoffeeMaker { constructor(coffeeBeans: number) { this.coffeeBeans = coffeeBeans; } makeCoffee() { return extractCoffee(); } } class LatteeMachine implements coffeeMaker { constructor(coffeeBeans: number) { this.coffeeBeans = coffeeBeans; } makeCoffee() { const coffee = extractCoffee(); return addMilk(coffee); } addMilk(coffee: CoffeeCup) { return { ...coffee, hasMilk: true, } } } // 참고: 드림코딩 엘리(https://academy.dream-coding.com/courses/typescript)
  • 정리
    • type, interface의 역할이 다르다. 그 역할에 따라 어떤 걸 쓰는게 맞을지 생각해보고 이용하자.
    • 예를들어, api 통신 후 받아올 때 Type, interface중 어떤 거로 정의하는 게 맞을까?
      • api 통신 후 받아오는 데이터에 대한 타입을 정의하는 것이기에, type이 더 적절하다고 생각한다. (특정 기능을 규정한 인터페이스는 적절하지 않아보인다)
      •