깜놀하는 해므찌로

typescript Generic 활용 예시 본문

IT

typescript Generic 활용 예시

agnusdei1207 2023. 5. 27. 13:10
반응형
SMALL
/** Generic */

function getSize<T>(arr:T[]){ // TypeParameter 일반적으로 T 사용
    return arr.length;
}

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

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

const arr3 = [true, false, true];
getSize(arr3); // 호출 시 제네릭 입력 생략 가능

/** 인터페이스 예시 */
interface Mobile<T>{
    name : string;
    price : number;
    option : T;
}

const mobile1:Mobile<object> = {
    name : "안드로이드",
    price : 1000,
    option : {
        color : "red",
        free : false
    }
}

const mobile2:Mobile<string> = {
    name : "아이폰",
    price : 10000,
    option : "greate"
}
interface User{
    name:string;
    age:number;
}

interface Car{
    name:string;
    color:string;
}

interface Book{
    price:string;
}

const user:User = {
    name : "이름",
    age : 10
};

const car:Car = {
    name : "Bmw",
    color : "red"
}

const book:Book = {
    price : "1000"
}

function showName<T extends {name:string}>(data:T):string{
    return data.name;
}

showName(user);
showName(car);
showName(book);
반응형
LIST