logoProsperBao

获取函数返回类型

2022-03-23 01

题目来源(type-challenges)

问题

不使用 ReturnType 实现 TypeScript 的 ReturnType<T> 泛型。

例如:

const fn = (v: boolean) => {
  if (v)
    return 1
  else
    return 2
}

type a = MyReturnType<typeof fn> // 应推导出 "1 | 2"

解答

type MyReturnType<T extends Function> = T extends (...args: any) => infer R ? R : never

拆分

  1. typeof fn 拿到对应变量的类型数据
  2. T extends Function 限制是个函数
  3. infer R 作为占位返回值