【问题标题】:TypeScript: how can I use a templated type without specifying the template parameter?TypeScript:如何在不指定模板参数的情况下使用模板类型?
【发布时间】:2021-07-05 04:20:14
【问题描述】:

最小的工作示例:

type FuncType<T> = (a: T) => T;

let f1: FuncType<T>; // does not compile
let f2: <T>(a: T) => T; // compiles

问题是FuncType不是我定义的,而是来自一个库。它也比上面的例子复杂得多。我想使用从库中导出的模板类型,而不必自己重新声明它(就像我在注释 f2 时所做的那样)。

有可能吗?如果没有,你知道为什么不吗?

感谢您的任何意见,我找不到有关此主题的任何内容

【问题讨论】:

  • declare let f1: FuncType&lt;T&gt;;
  • 不使用 TS 4.2.3 编译 - 你使用的是哪个编译器版本 @RobertoZvjerković?

标签: typescript templates generics types typescript-generics


【解决方案1】:

您不能将变量键入为未实例化的泛型类型。

&lt;T&gt;(a: T) =&gt; T 起作用的原因是因为这是一个通用函数。 FuncType&lt;T&gt;,定义为一个泛型类型,恰好是一个函数。不同之处在于,对于泛型函数,类型参数是在调用站点(每次调用)决定的,而对于泛型类型,类型是在声明变量时决定的,不受后续调用的影响。

type FuncType<T> = (a: T) => T;

declare let f1: FuncType<number>;
f1(1) // ok, T is number
f1("1") // not ok, T is still number
declare let f2: <T>(a: T) => T; 
f2(1) // ok, T is number 
f2("1") // also ok, T is now string

Playground Link

如果您想表示FuncType 的任何实例化,您最好的选择是FuncType&lt;any&gt;。但是您将不得不忍受相关的不安全感。 (unknownever 在这里不起作用,因为 FuncTypeT 中是不变的,它们分别适用于 type FuncType&lt;T&gt; = () =&gt; Ttype FuncType&lt;T&gt; = (a: T) =&gt; void

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 2018-02-28
    • 2012-10-11
    • 1970-01-01
    相关资源
    最近更新 更多