【问题标题】:Migrating from Flow to TypeScript: $Call<F, T...> equivalent in TS?从 Flow 迁移到 TypeScript:TS 中的 $Call<F, T...> 等价物?
【发布时间】:2020-03-10 20:13:00
【问题描述】:

Flow 有方便的$Call&lt;F, T...&gt; utility type,它可以获取调用 F 类型函数的返回类型,(可选)第一个参数为类型 T,第二个参数等等。所以我们可以这样做:

type First = <T>(Array<T>) => T | void;
type ShouldBeOptionalString = $Call<First, Array<string>>; // ShouldBeOptionalString is string | void

TypeScript 能否实现等效功能?我知道TypeScript提供的ReturnType&lt;T&gt; 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


    【解决方案1】:

    我相信要实现这样的目标,您必须将类型设为泛型,我猜每个参数都有一个单独的泛型:

    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 | void
    

    【讨论】:

    • 感谢您提供此解决方案,但我想要的类型来自我无法控制的代码,它来自另一个库,公开了一种泛型函数。
    猜你喜欢
    • 2019-07-02
    • 2010-09-27
    • 2010-10-16
    • 2020-05-24
    • 2017-04-12
    • 2012-05-10
    • 2011-12-08
    • 2010-11-10
    • 2020-03-28
    相关资源
    最近更新 更多