generic으로 지정하고 싶은 타입이 하나가 아닌 2개 이상 일때도 있다. 이때는 다음과 같이 작성한다.
// 2개 이상
function printHello<T, U, V>(message: T, comment: U): V{
return message;
}
// 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