【发布时间】:2020-03-10 20:13:00
【问题描述】:
Flow 有方便的$Call<F, T...> utility type,它可以获取调用 F 类型函数的返回类型,(可选)第一个参数为类型 T,第二个参数等等。所以我们可以这样做:
type First = <T>(Array<T>) => T | void;
type ShouldBeOptionalString = $Call<First, Array<string>>; // ShouldBeOptionalString is string | void
TypeScript 能否实现等效功能?我知道TypeScript提供的ReturnType<T> utility type,但是它不能根据参数类型计算返回类型:
type First = <T>(arg0: Array<T>) => T | void;
type WhatWillThisBe = ReturnType<First>; // WhatWillThisBe will be unknown
我尝试推出自己的 ReturnType 版本,它试图用给定的参数推断返回类型,但没有运气:
type CallWithArgsReturnType<T extends (...args: any) => any, A extends Array<any>> = T extends ((...args: A) => infer R) ? R : never;
type ShouldBeOptionalString = CallWithArgsReturnType<First, [Array<string>]>; // ShouldBeOptionalString will be unknown
【问题讨论】:
标签: typescript flowtype