TypeScript-섹션7. 제네릭-제네릭 인터페이스, 제네릭 타입 별칭(4)

손주완·2025년 7월 15일

Typescript Section7

목록 보기
4/6

✅ 선요약

  • 제네릭은 인터페이스, 타입 별칭, 함수 등에 적용 가능
  • 제네릭 인터페이스는 다양한 타입을 유연하게 표현할 수 있음
  • 인덱스 시그니처, 유니온 타입, 조건 분기, 함수 매개변수 제한 등 실용도가 높음
  • 타입 추론은 불가하므로 반드시 타입 인자를 명시해야 함

📌 기본 제네릭 인터페이스

interface KeyPair<K, V> {
  key: K;
  value: V;
}

let keyPair: KeyPair<string, number> = {
  key: "key",
  value: 0,
};

let keyPair2: KeyPair<boolean, string[]> = {
  key: true,
  value: ["1"],
};

📌 인덱스 시그니처 + 제네릭

interface Map<V> {
  [key: string]: V;
}

let stringMap: Map<string> = {
  key: "value",
};

let booleanMap: Map<boolean> = {
  key: true,
};

📌 제네릭 타입 별칭

type Map2<V> = {
  [key: string]: V;
};

let stringMap2: Map2<string> = {
  key: "string",
};

✅ 제네릭 인터페이스 활용 예

타입 정의

interface Student {
  type: "student";
  school: string;
}

interface Developer {
  type: "developer";
  skill: string;
}

제네릭 적용 전

interface User {
  name: string;
  profile: Student | Developer;
}

function goToSchool(user: User) {
  if (user.profile.type !== "student") {
    console.log("잘 못 오셨습니다");
    return;
  }

  const school = user.profile.school;
  console.log(`${school}로 등교 완료`);
}

제네릭 적용 후

interface User<T> {
  name: string;
  profile: T;
}

function goToSchool(user: User<Student>) {
  const school = user.profile.school;
  console.log(`${school}로 등교 완료`);
}

const developerUser: User<Developer> = {
  name: "이정환",
  profile: {
    type: "developer",
    skill: "TypeScript",
  },
};

const studentUser: User<Student> = {
  name: "홍길동",
  profile: {
    type: "student",
    school: "가톨릭대학교",
  },
};

✅ 마무리

제네릭 인터페이스는 객체 설계 시
다양한 타입을 유연하고 안전하게 다룰 수 있게 해주는 도구다.
함수, 타입 별칭, 조건 분기, 인덱스 구조 등과 조합하여 쓰면 매우 강력하다.

0개의 댓글