TypeScript - Generic

Boo Sung Jun·2022년 3월 22일
0

TypeScript

목록 보기
8/8
post-thumbnail

Generic

  • Generic은 타입을 전달하여 타입스크립트가 타입 추론을 제대로 하게 한다.
  function 함수<MyType, MyType2>(x: MyType[], y: MyType2[]): MyType {
    return x[0];
  }
  let x = 함수<number, string>([1, 2], ["3", "4"]);



  • generic을 이용하면 narrowing을 줄일 수 있다.
    타입스크립트는 함수에서 값을 입력할 때 타입을 알아서 변경해주지 않는다. 리턴 값이 애매한 경우 실제로 number 타입을 리턴하더라도 연산하면 에러가 날 수 있다. 따라서 narrowing을 하거나 generic을 이용한다.
  // Generic 사용하지 않았을 때
  function 함수(x: unknown[]) {
    return x[0];
  }
  let a = 함수([1, 2]);
  // a의 타입은 number가 아니라 unknown
  // 연산 하려면 narrowing 해야함
  console.log(a + 1);  // 에러

  // Generic을 사용했을 때
  function 함수2<MyType>(x: MyType[]): MyType {
    return x[0];
  }
  let b = 함수2<number>([1, 2]);
  console.log(b + 1);



Constraints

Generic 타입 제한을 둘 수 있다.

  function 함수<MyType extends number>(x: MyType): number {
    // 연산할 때 narrowing 할 필요 없음
    return x + 1;
  }

아래와 같이 커스텀 타입에도 적용 가능하다

  interface LengthCheck {
    length: number;
  }

  function 함수<MyType extends LengthCheck>(x: MyType): number {
    // 연narrowing 할 필요 없음
    return x.length;
  }



클래스에서 Generic 사용하기

클래스에서 generic을 사용할 땐, 클래스명 오른쪽에 타입을 적는다.

  class 클래스<T> {
    name;
    constructor(a: T) {
      this.name = a;
    }
  }

  let a = new 클래스<string>("John");
  console.log(typeof a.name);  // 출력: string

0개의 댓글