Flow有一个方便的$Call utility type,它可以获得调用类型F的函数的返回类型,第一个参数(可选)作为类型T,第二个参数等等。所以我们可以这样做:
type First = <T>(Array<T>) => T | void;
type ShouldBeOptionalString = $Call<First, Array<string>>; // ShouldBeOptionalString is string | voidTypeScript能实现同等的功能吗?我知道TypeScript提供的ReturnType 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 发布于 2020-03-10 20:06:24
我相信要实现这样的事情,你必须使类型泛型,我想每个参数都有一个单独的泛型:
type First<T = any> = (arg0: T[]) => T | void;
type WhatWillThisBe = ReturnType<First<string>>; // string | void如果你也希望这个函数是泛型的,你可以这样做:
type First<T = any> = <U extends T>(arg0: Array<U>) => U | void;
type WhatWillThisBe = ReturnType<First<string>>; // string | voidhttps://stackoverflow.com/questions/60616924
复制相似问题