제네릭 인터페이스, 제네릭 타입 별칭 - 제네릭

제네릭 인터페이스

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 NumberMap{
    [key: string]: number;
}

let numberMap: NumberMap = {
    key: -123,
    key2: 123123,
};

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 : "hello",
};

제네릭 인터페이스의 활용 예시

→ 유저 관리 프로그램

→ 유저 구분 : 학생 유저 / 개발자 유저

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

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

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

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

// goToSchool(developerUser) 제네릭 인터페이스를 사용해서 애초에 타입이 안맞아 에러 발생시켜 타입 좁히기를 사용할 필요 없음

const developerUser : User<Developer> = {
    name: "박정수",
    profile: {
        type: "developer",
        skill: "TypeScript",
    },
}

const studentUser : User<Student> = {
    name: "홍길동",
    profile: {
        type: "student",
        school: "한밭대학교",
    },
}