← 홈페이지 5강 목록으로
📐
EPISODE 03
interface · type · ? · readonly · | · &

인터페이스와 타입

interface와 type alias의 차이, 선택적 프로퍼티, readonly, 인터페이스 확장(extends), 유니온(|)과 교차(&) 타입, 인덱스 시그니처를 익힙니다.

interfacetypeunionintersection
소요 시간
45분
난이도
📊 중급
선수 조건
🎯 ts-02
결과물
복잡한 객체 형태를 정확히 모델링

이 강의에서 배우는 것

  • 1interface와 type 의 차이와 선택 기준을 안다
  • 2선택적(?)과 readonly 프로퍼티를 사용한다
  • 3extends로 인터페이스를 확장한다
  • 4유니온(|)과 교차(&) 타입을 작성한다
  • 5인덱스 시그니처로 동적 키를 표현한다

1. interface vs type alias

typescript
// interface
interface User {
  id: number;
  name: string;
  email: string;
}

// type alias
type User = {
  id: number;
  name: string;
  email: string;
};
기능interfacetype
선언 병합OX
확장extends& (교차)
유니온 정의XO
원시 타입 별칭XO
💡

관례: 객체 형태는 interface, 유니온/교차/원시 별칭은 type.

2. 선택적 프로퍼티 (?)

typescript
interface Product {
  id: number;
  name: string;
  price: number;
  description?: string;   // 있어도, 없어도 됨
  imageUrl?: string;
}

const product: Product = {
  id: 1,
  name: '노트북',
  price: 1500000,
};

3. readonly

typescript
interface Config {
  readonly apiKey: string;
  readonly baseUrl: string;
  timeout: number;
}

const config: Config = { apiKey: 'abc', baseUrl: '...', timeout: 3000 };
config.timeout = 5000;  // OK
config.apiKey = 'xyz';  // 오류: readonly

4. 인터페이스 확장 (extends)

typescript
interface Animal {
  name: string;
  age: number;
}

interface Dog extends Animal {
  breed: string;
}

const dog: Dog = { name: '멍멍이', age: 3, breed: '진돗개' };

5. 유니온 (|)

typescript
type ID = string | number;
type Status = 'pending' | 'active' | 'inactive';

let userId: ID = 123;
userId = 'user_abc';  // OK

let status: Status = 'active';
status = 'deleted';   // 오류: Status에 없음

6. 교차 타입 (&)

typescript
type Admin = User & {
  permissions: string[];
  level: number;
};

const admin: Admin = {
  id: 1, name: '관리자', email: 'admin@…',
  permissions: ['read', 'write'],
  level: 5,
};

7. 인덱스 시그니처

typescript
interface StringMap {
  [key: string]: string;
}

const translations: StringMap = {
  hello: '안녕하세요',
  goodbye: '안녕히 가세요',
};

translations.welcome = '환영합니다';
예제 코드 / 강의 자료

전체 강의 자료와 예제 코드는 GitHub에서 자유롭게 받아볼 수 있습니다.

GitHub에서 보기 ↗