[TypeScript] Generics(1)

haryun·2022년 9월 11일
0

TypeScript

목록 보기
5/6
post-thumbnail

패스트캠퍼스 TypeScript 강의 Ch 7. Generics 복습 내용
참고링크

📕 Generics 정리

📌 제네릭의 개념

제네릭은 다수의 데이터 타입에 대해 클래스/인터페이스 혹은 함수가 동일하게 동작할 수 있게 해주는 기능이다. (제네릭 클래스, 제네릭 인터페이스, 제네릭 함수 등을 사용할 수 있다.)

📌 Generics 기본 사용법

function func01<T>(message: T): T {
  return message;
}

func01<string>('Haryun');
func01(300); // 이 경우 T는 300이 됨. TS가 추론 가능한 가장 좁은 범위 내의 타입

function func02<T, U>(messsage: T, comment: U>: U {
	return comment;
} // 제네릭 타입 복수 지정 가능

func02<string, number>('Haryun', 20);

📌 Generics vs Any

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

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

위와 같이 일정한 규칙에 따라 특정 로직을 수행하는 함수가 반복적으로 필요한 경우를 가정하였을 때, Any와 Generic을 사용하여 함수를 간단히 작성할 수 있다.

1. Any의 경우

function hello(message: any): any {
  return message;
}
console.log(hello('Komma')); // any
console.log(hello(55).length); // any

any를 사용하면 함수 호출시 작성한 매개변수의 타입에 상관없이 어떤 값이든 any 타입으로 지정된다. (타입별로 사용 가능한 내장함수의 활용이 어려움)

2. Generic의 경우

function helloGeneric<T>(message: T): T {
  return message;
}

console.log(helloGeneric('Mark').length);
console.log(helloGeneric(39).length); // error
console.log(helloGeneric(true));

위와 같이 입력한 매개변수의 타입별로 구분이 가능하다. (number 타입의 매개변수를 사용하는 경우 string 객체의 내장함수 .length 를 사용할 수 없다.)

📌 Generics Array & Tuple

// 제네릭으로 배열과 튜플 표현
function helloArray<T>(message: T[]): T {
  return message[0];
}

helloArray(['haryun', 'harin']); // <string>
helloArray(['hello', 5]); // <string | number> 반환값을 유니온 타입으로 유추

function helloTuple<T, K>(message: [T, K]): T {
  return message[0];
}

helloTuple(['haryun', 'harin']); //
helloTuple(['hello', 5]); //<string, number> Array보다 정확한 추론 가능

정확한 타입 추론이 필요한 경우 tuple을 활용하여 함수를 작성할 수 있다.

📌 Generics 함수

제네릭을 사용하여 함수의 타입만 지정하는 경우.

// 1.type alias
type helloFunctionGeneric01 = <T>(message: T) => T;

const func01: helloFunctionGeneric01 = <T>(message: T): T => {
  return message;
};

// 2. interface
interface helloFunctionGeneric02 {
  <T>(message: T): T ;
}

const func02: helloFunctionGeneric02 = <T>(message: T): T => {
  return message;
};

0개의 댓글