Skip to content
Onsite

MyReturnType<T>

MediumP1Coding

Implement the built-in ReturnType<T> generic without using it.

MyReturnType<T> is the type a function type T returns. T must be restricted to function types.

Tests your type must pass

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>>>,
  // @ts-expect-error a string is not a function type
  MyReturnType<string>,
]

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)

Hints

TypeScript
Run and Submit type-check your solution against the tests.