TypeScript - Generics<1> 제네릭, 제네릭타입

CH_Hwang·2022년 2월 23일
0

TypeScript

목록 보기
1/12

제네릭

코드의 재사용성을 늘려주기 위한 도구

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

위 코드의 경우 number라는 타입에 한정되어있다.
이를 해결하기위해서는?

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

위처럼 작성할 수 있다. 하지만 이경우에 arg와 return이 다르게 될 수 있다.

이를 해결하기위해 제네릭을 사용하게 되면 아래와 같다.

function identity<T>(arg:T):T {
  return arg
}

위와 같이 작성했을때 타입 변수가 추가되어 사용자가 작성한 타입을 따르게 된다.

any를 사용했을때와는 다르게 tpye 범위 내에서 동작하는 이 identity 함수를 제네릭이라고 한다.
그리고 맨 위에 작성한 코드만큼 정확하게 동작한다.

let output = identity<string>("string");
console.log(typeof output) // string

Generic Types

제네릭 함수의 타입은 함수 선언과 비슷하다

function identity<Type>(arg: Type): Type {
  return arg
}

let myIdentity: <Type>(arg: Type) => Type = identity;

타입의 제네릭 타입파라미터에 타입변수들을 사용할 수 있다.

function identity<Type>(arg: Type): Type {
  return arg
}

let myIdentity: <Input>(arg: Input) => Input = identity;

객체 타입의 call signature로 제네릭 타입을 사용할 수도 있다.

function identity<Type>(arg: Type): Type {
  return arg;
}
 
let myIdentity: { <Type>(arg: Type): Type } = identity;

call signature

자바스크립트의 타입표현문법은 프로퍼티를 정의하는 것을 허락하지 않음.
그렇기 때문에 우리는 객체 타입의 call signature를 써서 프로퍼티들을 설명해야함

type DescribableFunction = {
  description: string;
  (someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
  console.log(fn.description + " returned " + fn(6));
}

위에서 call signature로 제네릭 타입을 사용한 것을 generic interface를 이용하면 아래와 같다.

interface GenericIdentityFn {
  <Type>(arg: Type): Type;
}
 
function identity<Type>(arg: Type): Type {
  return arg;
}
 
let myIdentity: GenericIdentityFn = identity;
let myIdentity: GenericIdentityFn<string> = identity; //사용

0개의 댓글