⚙️ 4. TypeScript에서 `interface`랑 `type`, 언제 뭘 써야 할까?

JM_Dev·2025년 4월 17일
1
post-thumbnail

처음 타입스크립트를 쓸 때 interfacetype이 너무 비슷해 보여서 헷갈렸다.
실제로 대부분 상황에선 둘 다 쓸 수 있는데, 미묘한 차이들이 있어서 정리해봤다.


✅ 공통점

  • 객체 타입 정의할 수 있음
interface User {
  name: string;
  age: number;
}

type User = {
  name: string;
  age: number;
}
  • 둘 다 extends 가능

✅ 차이점

1) 확장 방식

  • interface는 확장이 직관적
interface Animal {
  name: string;
}
interface Dog extends Animal {
  breed: string;
}
  • type은 유니온이나 인터섹션으로 조합
type Animal = {
  name: string;
}
type Dog = Animal & {
  breed: string;
}

2) 유니온/튜플/프리미티브는 type만 가능

type Status = "loading" | "success" | "error";

type Point = [number, number];

type Custom = string | number;

3) 선언 병합은 interface만 가능

interface Box {
  width: number;
}
interface Box {
  height: number;
}

// Box = { width: number; height: number; }

type은 이렇게 중복 선언하면 오류 남


✅ 그럼 어떤 걸 써야 할까?

  • 객체 중심, 확장이 많은 구조면 interface
  • 유니온, 튜플, 조건부 타입 등 복잡한 조합은 type
  • 혼용도 가능하지만 코드 컨벤션은 통일하는 게 좋음!

📝 내가 느낀 점

개인적으로는 구조적인 타입 정의나 컴포넌트 props 같은 경우는 interface가 더 읽기 편했고,
상태나 특정 타입 조합에는 type이 훨씬 자유롭게 느껴졌다.
처음에는 차이를 모르고 막 썼는데, 이제는 목적에 따라 골라 쓰는 게 중요하다는 걸 알게 됐다.


"타입스크립트는 자유롭지만, 그 자유엔 책임이 따른다..."

profile
개발자로 취업을 준비 중 이며, 열심히 공부 중 입니다!

0개의 댓글