ReturnType
ReturnType 是 typescript 的内置泛型,用于提取函数类型的返回值类型。
function foo(): number {
return 42;
}
type T = ReturnType<typeof foo>; // T 的类型为 number
实现
type myReturnType<T> = T extends (...args: any) => infer P ? P : any;
const fn = (v: boolean) => {
if (v)
return 1
else
return 2
}
type a = myReturnType<typeof fn> // a: 1 | 2