Learning
레슨 2 / 8·20분

인터페이스와 타입

interface와 type의 차이

interface는 객체의 구조를 정의하는 데 사용되며, type은 Union, Intersection 등 더 넓은 범위의 타입 별칭을 만들 수 있습니다. 객체 모양을 정의할 때는 interface, 복합 타입에는 type을 사용하는 것이 일반적입니다.

typescript
// interface — 객체 구조 정의
interface User {
  id: number;
  name: string;
  email: string;
  age?: number;  // 선택적 속성 (optional)
}

const user: User = {
  id: 1,
  name: "김철수",
  email: "kim@example.com",
};

// type 별칭 — 다양한 타입 조합
type ID = string | number;
type Status = "active" | "inactive" | "banned";

인터페이스 확장과 교차 타입

typescript
// interface 확장 (extends)
interface Animal {
  name: string;
  age: number;
}

interface Dog extends Animal {
  breed: string;
}

const myDog: Dog = {
  name: "멍멍이",
  age: 3,
  breed: "골든리트리버",
};

// type 교차 타입 (Intersection)
type WithTimestamp = {
  createdAt: Date;
  updatedAt: Date;
};

type Post = {
  title: string;
  body: string;
} & WithTimestamp;
  • interfaceextends로 확장, 선언 병합(declaration merging) 가능
  • type — Union(|), Intersection(&) 등 조합이 자유로움
  • ? — 선택적 속성 표시, 없어도 에러가 나지 않음
  • readonly — 읽기 전용 속성, 재할당 시 컴파일 에러
💡

팀에서 일관된 규칙이 없다면, 객체 형태는 interface, 그 외에는 type을 사용하는 것을 추천합니다.