View on GitHub: https://tsch.js.org/2 */ /* _____________ Your Code Here _____________ */ type MyReturnType = any /* _____________ Test Cases _____________ */ import { Equal, Expect } from '@type-challenges/utils' type cases = [ Expect string>>>, Expect 123>>>, Expect ComplexObject>>>, Expect, MyReturnType<() => Promise>>>, Expect 'foo', MyReturnType<() => () => 'foo'>>>, Expect>>, Expect>>, ] "> View on GitHub: https://tsch.js.org/2 */ /* _____________ Your Code Here _____________ */ type MyReturnType = any /* _____________ Test Cases _____________ */ import { Equal, Expect } from '@type-challenges/utils' type cases = [ Expect string>>>, Expect 123>>>, Expect ComplexObject>>>, Expect, MyReturnType<() => Promise>>>, Expect 'foo', MyReturnType<() => () => 'foo'>>>, Expect>>, Expect>>, ] "> View on GitHub: https://tsch.js.org/2 */ /* _____________ Your Code Here _____________ */ type MyReturnType = any /* _____________ Test Cases _____________ */ import { Equal, Expect } from '@type-challenges/utils' type cases = [ Expect string>>>, Expect 123>>>, Expect ComplexObject>>>, Expect, MyReturnType<() => Promise>>>, Expect 'foo', MyReturnType<() => () => 'foo'>>>, Expect>>, Expect>>, ] ">
/*
  2 - Get Return Type
  -------
  by Anthony Fu (@antfu) #medium #infer #built-in
  
  ### Question
  
  Implement the built-in `ReturnType<T>` generic without using it.
  
  For example
  
  ```ts
  const fn = (v: boolean) => {
    if (v)
      return 1
    else
      return 2
  }
  
  type a = MyReturnType<typeof fn> // should be "1 | 2"

View on GitHub: https://tsch.js.org/2 */

/* _____________ Your Code Here _____________ */

type MyReturnType<T> = any

/* _____________ Test Cases _____________ */ import { Equal, Expect } from '@type-challenges/utils'

type cases = [ Expect<Equal<string, MyReturnType<() => string>>>, Expect<Equal<123, MyReturnType<() => 123>>>, Expect<Equal<ComplexObject, MyReturnType<() => ComplexObject>>>, Expect<Equal<Promise<boolean>, MyReturnType<() => Promise<boolean>>>>, Expect<Equal<() => 'foo', MyReturnType<() => () => 'foo'>>>, Expect<Equal<1 | 2, MyReturnType<typeof fn>>>, Expect<Equal<1 | 2, MyReturnType<typeof fn1>>>, ]

type ComplexObject = { a: [12, 'foo'] bar: 'hello' prev(): number }

const fn = (v: boolean) => v ? 1 : 2 const fn1 = (v: boolean, w: any) => v ? 1 : 2

/* _____________ Further Steps _____________ / /

Share your solutions: https://tsch.js.org/2/answer View solutions: https://tsch.js.org/2/solutions More Challenges: https://tsch.js.org */


제네릭을 실행 시켜야 하나? 어떻게 하지?

조건부 타입을 사용하고 조건부 타입 `extends` 절에서 추론된 타입을 변수로 사용 가능하게 하는 `infer` 절을 이용하자!

```tsx
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : any
  • 제네릭이 함수 형태 라면 리턴으로 추론된 타입을 R 로 변수로 담아 리턴하고 아니면 any를 리턴

추천된 솔루션을 보자

type MyReturnType<T extends Function> = T extends (...args: any) => infer R ? R : never
  • 더 깔끔하고 스트릭 한 것 같다.