【问题标题】:Class in generic and as literal in TypeScript泛型类和 TypeScript 中的字面量
【发布时间】:2018-10-15 21:57:20
【问题描述】:

在 Java 中,我们可以执行以下操作:

Map<Class<?>, Integer> countsByClass;
...
countsByClass.put(String.class, 1);

如何在 TypeScript(或类似的东西)中做同样的事情?

let countsByClass: Map<???, Number>;
...
countsByClass.put(???, 1);

【问题讨论】:

  • 你不是说泛型类吗?喜欢地图

标签: typescript


【解决方案1】:

以下应该这样做:

class Foo {}

let countsByClass: Map<new (...args: any[]) => any, number> = new Map();
countsByClass.set(Foo, 5);

console.log(countsByClass.get(Foo));

也可以定义一个中间的Class类型:

type Class<T = any> = new (...args: any[]) => T;

然后Map 声明变得更清晰:

let countsByClass: Map<Class, number> = new Map();

Stackblitz demo

【讨论】:

  • 查看this answer 的类似问题,了解有关new (...args: any[]) =&gt; any 为何有效的更多信息
  • 你能解释一下这个new (...args: any[]) =&gt; any吗?
  • @Pavel_K 这是blog post 解释它。一个有趣的部分是The type Constructor&lt;T&gt; is an alias for the construct signature that describes a type which can construct objects of the generic type T and whose constructor function accepts an arbitrary number of parameters of any type.Constructor 在我的回答中相当于Class。)
【解决方案2】:

我认为您的意思是为类提供泛型类型。当然,如果需要,您可以提供多种类型。

例子:

class Map<T, U> { }

如果我错了,请纠正我。

【讨论】:

    猜你喜欢
    • 2018-11-03
    • 2018-02-01
    • 2019-05-30
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2019-07-05
    • 2018-08-04
    相关资源
    最近更新 更多