// From the hover popup
// const myFunc: () => string

const myFunc = () => {
  return "hello"
}

우린 myFunc 가 반환하는 타입을 MyFuncReturn 안에 넣고 싶습니다.

type MyFuncReturn = unknown

물론 수동으로 타입을 추가할 수도 있지만, myFunc 의 반환이 변경되면 타입이 더 이상 동일하지 않을 수 있습니다. 이 작업을 수행하려면 Typescript 문서에서 유틸리티 타입을 찾을 뿐만 아니라 typeof 연산자를 사용해야 합니다.

나의 답

import { Equal, Expect } from '../helpers/type-utils';

const myFunc = () => {
  return 'hello';
};

type Return<T> = T extends (...args: any[]) => infer R ? R : never;

/**
 * How do we extract MyFuncReturn from myFunc?
 */
// type MyFuncReturn = Return<typeof myFunc>;
type MyFuncReturn = ReturnType<typeof myFunc>;

type tests = [Expect<Equal<MyFuncReturn, string>>];

Use a Utility Type to Extract a Function’s Return Type

솔루션은 두 부분입니다.

먼저 ReturnType 타입 헬퍼를 사용해야 합니다.

type MyFuncReturn = ReturnType<typeof myFunc>

좀 더 세분화하여 다음 코드 줄을 살펴봅시다.

type MyFunc = typeof myFunc

myFunc 타입 시그니쳐에서 정보를 가져와서 MyFunc 타입에 할당합니다.

이 패턴은 런타임코드에서 타입을 추출할 수 있기 때문에 매우 강력합니다.