【发布时间】: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
如果没有办法做到这一点,可以通过创建作为函数类型级别版本的类型别名来解决特定情况下的问题,如下面的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