TypeScript 합시다

[TypeScript][ch7][Generic] Generic, Any와 다른 점

써치킴 2022. 2. 18. 00:44

Generic

데이터의 타입을 일반화한다(generalize)는 것을 의미한다.

자료형을 정하지 않고 여러 타입을 사용할 수 있게 해준다.

선언 시점이 아니라 생성 시점에 타입을 명시하여 다양한 타입을 사용할 수 있도록 하는 기법이다.

Generic을 사용하지 않으면

function helloString(message: string): string {
  return message;
}

function helloNumber(message: number): number {
  return message;
}

↑ 1. 타입을 미리 정하거나

// 모든 타입을 받고 모든 타입을 리턴할 수 있음 -> Any...?

function hello(message: any): any {
  return message;
}

// .length는 string에 사용하는 메소드이지만 any타입이기 때문에 사용할 수 있다.
console.log(hello('Searchkim').length);
// 하지만 number, boolean과 같은 타입에 사용하면 undefined가 출력된다. 
console.log(hello(39).length);    // undefined
console.log(hello(true).length);  // undefined

↑ 2. any 타입을 사용할 수 있다.

 

그러나, 타입을 미리 정하면 항상 같은 타입을 받아야하기 때문에 범용성, 활용성이 떨어지고

any 타입을 사용하면 어떤 타입이 리턴되는지 예측할 수 없다. 

이러한 문제때문에 타입을 인수를 활용해서 리턴 타입에 연관을 주는 generic을사용한다!

// <T> : 타입이라고 생각하면 됨
// 함수 안에서 T를 기억. 
function helloGeneric<T>(message: T){
  return message;
}

// Anna라는 리터럴 타입으로 추론됨 -> string
console.log(helloGeneric('Anna'));
console.log(helloGeneric('Anna').length);

// 39라는 리터럴 타입으로 추론됨 -> number
console.log(helloGeneric(39));
// number형으로 추론되었으니 string형에서 사용하는 .length 메서드는 당연히 사용 불가
// console.log(helloGeneric(39).length);     // Error 발생

// true라는 리터럴 타입으로 추론됨 -> boolean
console.log(helloGeneric(true));