【问题标题】:How can I get the type of a function application in TypeScript?如何在 TypeScript 中获取函数应用程序的类型?
【发布时间】:2020-06-16 20:32:57
【问题描述】:

如何在 TypeScript 中获取应用于参数的泛型函数的类型?

例如,我如何在下面定义Apply

declare function f<T>(t: T): T extends number ? boolean : object;

type ResForNumArg = Apply<typeof f, number>;    // should be boolean
type ResForStringArg = Apply<typeof f, object>; // should be object

playground link

如果没有办法做到这一点,可以通过创建作为函数类型级别版本的类型别名来解决特定情况下的问题,如下面的F

declare function f<T>(t: T): T extends number ? boolean : object;
type ApplyF<T> = T extends number ? boolean : object;

type ResForNumArg = ApplyF<number>;    // boolean
type ResForStringArg = ApplyF<object>; // object

但是ApplyF 可能与f 不同步,并且打字很烦人。有没有更好的办法?

更新:这似乎与https://github.com/microsoft/TypeScript/issues/29043有关

【问题讨论】:

    标签: typescript generics typescript-generics typescript-declarations


    【解决方案1】:

    正如您正确发现的那样,不能将函数声明用作泛型类型,因此在没有函数执行的情况下无法应用泛型。我们只能在函数调用期间应用泛型(或从参数推断):

    const r1 = f<number>(1) //  boolean
    const r2 = f(1) // boolean
    

    好的,所以我们知道这是不可能的。现在的解决方法是,为了让它在不失去与原始声明的联系的情况下工作,我建议使用额外的泛型类型FType。考虑:

    type FType<T> = (t: T) => T extends number ? boolean : object;
    // join function declaration with FType:
    declare function f<T>(...t: Parameters<FType<T>>): ReturnType<FType<T>>
    
    type ResForNumArg =  ReturnType<FType<number>>;    // bool 
    type ResForStringArg = ReturnType<FType<object>>;  // object
    

    通过使用实用程序类型ParametersReturnType,我将FType 与函数f 声明连接起来。它很冗长,但我们最终得到了我们想要的,FType 可以以标准方式应用。

    Playground link

    【讨论】:

    • 删除 [0] 以支持 ...t
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    相关资源
    最近更新 更多