Get Return Type
问题描述
不使用 ReturnType 实现 TypeScript 的 ReturnType<T> 泛型。
例如:
const fn = (v: boolean) => {
if (v)
return 1
else
return 2
}
type a = MyReturnType<typeof fn> // 应推导出 "1 | 2"
// ============= Test Cases =============
import type { Equal, Expect } from './test-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)
// ============= Your Code Here =============
// 答案
type MyReturnType<T extends (...args: any) => unknown> = T extends (...args: any) => infer U? U: never
这是第一道中等难度的题,需要实现内置 Typescript 类型 ReturnType ,也就是函数返回值的类型,这里首先需要约束泛型参数的类型为函数类型,如果使用 T extends Function ,这里的 Function 包括了构造函数 class ,所以缩小范围,还是使用 T extends (...args: any) => unknown 来约束参数的类型,其次,我们需要获取到返回值,和获取形参的方法相同,还是构造一个三元表达式,并且使用关键字 infer 将推断的结果保存在泛型 U 中即可 T extends (...args: any) => infer U。