티스토리 뷰

[TS] 타입스크립트 Generic 예시코드

타입스크립트에서 Generic은 유연한 Type 설정을 가능하게 해줍니다.

예시 코드와 함께, 어떻게 사용하는지 확인해 봅시다.

 

@ Generic 사용예시 - 1 : 함수

// 아래와 같이 Generic타입을 선언할 수 있습니다.
// 이때 T는 다른 알파벳으로 사용해도 되지만 일반적으로 T를 사용합니다.
function getSize<T>(arr: T[]) : number{
    return arr.length;
}

// 값을 선언할때는 꺽쇠안에 타입을 지정해 줄 수 잇습니다.
const arr1 = [1,2,3];
getSize<number | string>(arr1);

const arr2 = ["a", "b", "c"];
getSize<string>(arr2);

// 꺽쇠로 타입을 지정해주지 않으면, 자동으로 타입이 지정됩니다.
// arr3에 커서를 두면 자동으로 지정된 타입을 다음과 같이 확인 할 수 있습니다
// 'const arr3: (string | number)[]' 
const arr3 = ["a", "1" , 3];

@ Generic 사용예시 - 2  : 객체

// option 타입이 generic인 interface를 선언합니다.
interface Mobile<T> {
    name : string;
    price : number;
    option  : T;
}
// option 타입에, 타입을 명시해주지 않아도, 자동으로 타입이 지정됩니다.
const m1: Mobile<object> = {
    name : "s21",
    price : 1000,
    option : {
        color : 'red',
        coupon : false,
    }
}
// 꺽쇠를 사용해, option에 특정타입을 한정해줄 수도 있습니다.
const m2: Mobile<{color : string; coupon : boolean}> = {
    name : "s21",
    price : 1000,
    option : {
        color : 'red',
        coupon : false,
    }
}

@ Generic 사용예시 -3 : extend로 타입 확장하기.

interface User {
    name : string;
    age : number;
}

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

interface Book {
    price : number;
}

const user : User = {name : "a", age : 10};
const car : Car = { name : "bmw", color : "red"};
const book: Book = { price : 3000 };
// showName함수는 객체에서 name값을 return해주는 함수입니다.
// Typescript가 객체안에 name의 타입까지는 확인 할 수 없으므로
// extends로 타입에 {name : string}을 확장해줍니다.
function showName<T extends {name : string}>(data : T) : string{
    return data.name
}

showName(user);
showName(car);
// showName(book); book객체에는 name 값이 없기 때문에 에러가 납니다.
댓글
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함