다음과 같은 제약들이 자주 쓰입니다. 각각 타입 매개변수가 객체, 배열, 함수, 생성자, 속성의 키여야 한다는 제약을 나타냅니다.

    <T extends object> // 모든 객체
    <T extends any[]> // 모든 배열
    <T extends (...args: any) => any> // 모든 함수
    <T extends abstract new (...args: any) => any> // 생성자 타입
    <T extends keyof any> // string | number | symbol
    

    제네릭에 제약을 사용할 때 흔히 하는 실수가 있습니다. 타입 매개변수와 제약을 동일하게 생각하는 것입니다.

    interface VO {
      value: any;
    }
    
    const returnVO = <T extends VO>(): T => {
      return { value: 'test' };
    }
    // Type '{ value: string; }' is not assignable to type 'T'. '{ value: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'VO'.
    
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.