Typescript의 Generic (2. 기초 사용)

eeensu·2023년 8월 7일
0

typescript

목록 보기
16/22
post-thumbnail

중복 지정 가능

generic으로 지정하고 싶은 타입이 하나가 아닌 2개 이상 일때도 있다. 이때는 다음과 같이 작성한다.

// 2개 이상 
function printHello<T, U, V>(message: T, comment: U): V{
    return message;
}



Array 또는 Tuple도 가능

// Array
function helloBasic<T>(msg: Array<T>): T {
    return msg[0];
}

const arr: string[] = ['안녕', '하세요'];
console.log(helloBasic<string>(arr));			 // 안녕
// Tuple
function helloTuple<T, U>(msg: [T, U]): T{
    return msg[0];
}

const tuple1: [string, string] = ['hi', 'hello'];
const tuple2: [string, number] = ['you', 65];

console.log(helloTuple(tuple1));							// hi
console.log(helloTuple(tuple2));							// you



함수의 타입 정의

위와 같이 함수 자체에 적용하는 generic타입이 아닌, 오리지널 형태의 함수 타입을 정의하여 generic을 typing 할 수 있다. 예를 통해 살펴보자.

// type aliasing 지정법
type HelloGenericType = <T>(msg: T) => void;

const hello1: HelloGeneric = (msg) => {
    console.log(msg);
}

hello1<string>('this is water');				 // this is water
// interface 지정법
interface IHelloGeneric {
    <T>(msg: T): void;
}

const hello2: IHelloGeneric = <T>(msg: T) => {
    console.log(msg);
};

hello2<boolean>(true);					  		// true
profile
안녕하세요! 26살 프론트엔드 개발자입니다! (2024/03 ~)

0개의 댓글