https://www.typescriptlang.org/docs/handbook/2/generics.html
function identity(arg: number): number {
return arg;
}
만약 다른 타입도 받을 수 있도록 하려면 어떻게 구성해야 하는지?
function identity(arg: any): any {
return arg;
}
모든 타입마다 이것을 작성해야 하는가?
이것 또한 함수의 이름이 중복되어 허용되지 않음
function identityNum(arg: number): number {
return arg;
}
function identityStr(arg: string): string {
return arg;
}
function identityBool(arg: boolean): boolean {
return arg;
}
//...
function identityObj1(arg: obj1): obj1 {
return arg;
}
function identityObj2(arg: obj2): obj2 {
return arg;
}
interface obj1 {
//...
}
interface obj2 {
//...
}
//...
⏩ 이런 비효율적인 상황을 대처하기 위한 것이 Generics임
<> 안에 작성된 키워드가 해당 함수에 동일한 표현들을 동적으로 통일시킨다는 것을 나타냄
통일될 최초 타입은 키워드가 작성된 Parameter의 타입이 기준이 되며 해당 블록의 키워드가 포함된 타입들은 모두 이를 따르게 됨
// Use Generics
function identity<Type>(arg: Type): Type {
return arg;
}
Type이란 키워드 대신 T라는 키워드로 대체하여 사용하는 경우 많음
// Use Generics
function identity<T>(arg: T): T {
return arg;
}
자유롭게 지정할 수 있어 타입 별칭과 혼동될 수 있지만 다른 기능
관례적으로 T를 매개 변수가 2개 이상을 제너릭으로 표현해야 하는 경우엔 이후로는 U,V,W 등을 자주 사용함
function identity<T, U>(arg1: T, arg2: U): [T, U] {
return [arg1, arg2];
}
const result = identity(20, "Hello"); // result는 [number, string] 타입
정확히 구분되는지 테스트
function isNumber(value: any) {
return typeof value === 'number' && !isNaN(value);
}
function isString(value: any) {
return typeof value === 'string';
}
// isArray는 Array의 내장 함수 사용
// 간단 테스트
// given
const testValue1: number = 20;
const testValue2: string = "Hi";
const testValue3: number[] = [1, 20];
// when 1
const numberIdentity = identity(testValue1); // number 타입
// then 1
console.log(`Input type is : ${typeof testValue1}`);
console.log(`Output type is : ${typeof numberIdentity}`);
console.log(`Is number: ${isNumber(numberIdentity)}`); // true
// when 2
const stringIdentity = identity(testValue2); // string 타입
// then 2
console.log(`Input type is : ${typeof testValue2}`);
console.log(`Output type is : ${typeof stringIdentity}`);
console.log(`Is string: ${isString(stringIdentity)}`); // true
// when 3
const arrayIdentity = identity(testValue3); // number[] 타입
// then 3
console.log(`Input type is : ${typeof testValue3}`);
console.log(`Output type is : ${typeof arrayIdentity}`);
console.log(`Is array: ${Array.isArray(arrayIdentity)}`) // true