Typescript의 유틸리티 타입 (4)

eeensu·2024년 8월 12일
0

typescript

목록 보기
22/22

ReturnType<T>

ReturnType 타입은 함수의 리턴값의 타입을 지정해주는 유틸리티 타입이다. Generic 인자로 typeof 키워드와 함께 추론할 함수를 넣어주면, 해당 함수의 리턴 타입을 반환한다.

type T0 = ReturnType<() => string>							   // string
type T1 = ReturnType<(s: string) => void>					   // void
type T2 = ReturnType<<T>() => T>							   // unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T> // number[]

Functuon 타입을 인자로 전달하면 다음의 에러가 발생한다.

type T8 = ReturnType<Function>; 
// Type 'Function' provides no match for the signature '(...args: any): any'.


Parameters<T>

함수 타입에서 매개변수의 타입들을 추출하여 새로운 튜플 타입(tuple type)을 생성시켜준다.

const logDetails = (a: string, b: number): void => {
    console.log(`a: ${a}, b: ${b}`);
};

// Parameters 유틸리티 타입을 사용해 매개변수 타입 추출
type LogDetailsParams = Parameters<typeof logDetails>;

// wrapperFunction 함수를 화살표 함수로 변환
const wrapperFunction = (...args: LogDetailsParams): void => {
    console.log('Calling logDetails with:', args);
    logDetails(...args);
};


InstanceType<T>

클래스 타입에서 해당 클래스의 인스턴스 타입을 추출하는 데 사용된다. 즉, 특정 클래스의 인스턴스를 생성했을 때 그 인스턴스가 가지게 되는 타입을 얻어낼 수 있다. 이 유틸리티 타입은 클래스 자체가 아닌, 클래스의 인스턴스가 어떤 타입을 가지는지를 알고 싶을 때 유용하다. 하지만 클래스 타입에만 사용 가능하며, 생성자를 정의하지 않은 클래스는 제한된다.

class ExampleClass {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    greet() {
        return `Hello, my name is ${this.name}.`;
    }
}

// `ExampleInstanceType`는 `ExampleClass`의 인스턴스 타입이 된다.
type ExampleInstanceType = InstanceType<typeof ExampleClass>;

const instance: ExampleInstanceType = new ExampleClass('John', 30);

console.log(instance.greet()); // 출력: Hello, my name is John.

하지만 대부분의 상황에선, 클래스 그 자체를 타입으로 쓰기에 InstanceType 을 사용하는 경우는 많지 않다. 그런데도 사용되는 이유는, 제너릭 클래스에서의 유연한 타입 추론과 생성자 함수에서도 사용하는 경우가 있을 수 있기 때문에 존재한다.

profile
안녕하세요! 26살 프론트엔드 개발자입니다! (2024/03 ~)

0개의 댓글