https://www.typescriptlang.org/docs/handbook/2/generics.html

Generics


function identity(arg: number): number {
  return arg;
}

만약 다른 타입도 받을 수 있도록 하려면 어떻게 구성해야 하는지?

function identity(arg: any): any {
  return arg;
}

모든 타입마다 이것을 작성해야 하는가?

정확히 구분되는지 테스트

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