본문 바로가기

Dev/Typescript

타입스크립트 Typescript 제네릭

Typescript

// Generic
function getSize<T>(arr: T[]): number {
    return arr.length;
}

const arr1 = [1, 2, 3];
getSize<number>(arr1);

const arr2 = ["1", "2", "3"];
getSize<string>(arr2);


interface Mobile<T> {
    name: string;
    price: number;
    option: T;
}

const m1: Mobile<{ color: string; coupon: boolean; }> = {
    name: "s21",
    price: 1000,
    option: {
        color: "red",
        coupon: false,
    }
}

const m2: Mobile<string> = {
    name: "s20",
    price: 900,
    option: "good"
}


interface User {
    name: string;
    age: number;
}
interface Car {
    name: string;
    color: string;
}
const user: User = { name:"a", age:10 };
const car: Car = { name:"bmw", color:"red" };
function showName<T extends { name: string }>(data: T): string {
    return data.name;
}

showName(user);
showName(car);