【类型挑战】获取函数返回类型,难度⭐️⭐️

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第14天,点击查看活动详情

Dear,大家好,我是“前端小鑫同学”,😇长期从事前端开发,安卓开发,热衷技术,在编程路上越走越远~


知识运用:

  1. 认识什么是returntypetype

题目分析:

题目地址:2-medium-return-type image.png 如上图所示,我们需要设计一个通用了类型工具还提取函数类型的返回类型,功能同内置的ReturnType。

题目解答:

测试用例:

给出的测试用例挺多但是没有特殊需要说明的,我们只需要通过设计的类型工具取出到通过Equal来进行比较即可。

/* _____________ 测试用例 _____________ */
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

答案及解析:

  1. 其实在上一题中我们已经提取到函数类型参数的类型了,我们这次修改为提取返回值的类型即可,我们此次传入的类型T可以使用泛型约束输入,也不可不用约束,因为我们还是会用到条件类型来进行判断。可以省去输入类型约束。
  2. 同样采用条件类型+infer来进行提取,将infet占位return的位置,用R来代替,如果T可分配到右侧则返回R,否则返回never;
/* _____________ 你的代码 _____________ */

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

去演练场验证答案

接下来的一题是:【类型挑战】实现 Omit,难度⭐️⭐️


欢迎关注我的公众号“前端小鑫同学”,原创技术文章第一时间推送。

posted @ 2022-04-14 00:04  前端小鑫同学  阅读(9)  评论(0)    收藏  举报  来源