lxxmnmn / type-challenges

TypeScript type challenges
https://tsch.js.org/
MIT License
0 stars 0 forks source link

2 - Get Return Type #15

Open lxxmnmn opened 2 months ago

lxxmnmn commented 2 months ago

Get Return Type medium #infer #built-in

내장 제네릭 ReturnType<T>을 이를 사용하지 않고 구현하세요.

/* _____________ Your Code Here _____________ */

type MyReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : never;
/* _____________ Test Cases _____________ */

import type { 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
lxxmnmn commented 2 months ago

8

14