【问题标题】:How to declare a Map<T, K> which T should be a variadic class and K should be an instance of T?如何声明一个 Map<T, K>,其中 T 应该是可变参数类,K 应该是 T 的实例?
【发布时间】:2021-08-14 17:53:51
【问题描述】:

我想声明一个Map&lt;T, K&gt; 类型,映射中的键是类,映射的值应该是对应键的实例。例如:

class X {}

type InstanceMap = // the type that I want to declare

const map: InstanceMap = new Map();
map.set( X, new X() );

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    我认为这是不可能的,它需要existentially quantified generic types。你可以这样做

    type InstanceMap<T> = Map<{new (): T}, T>
    

    使用constructor type 作为密钥,但这只会允许您存储特定的类(可能还有子类?)而不是任何 类。您的代码可以使用const map: InstanceMap&lt;X&gt; = new Map(); 编译,但map.set(Y, new Y()) 会失败。

    与其尝试实例化 Map 类型,不如尝试提出我们自己的接口,其中存在量词被委托给各个方法:

    interface InstanceMap {
        set<T>(c: new () => T, i: T): void;
        get<T>(c: new () => T): T | undefined;
    }
    

    这适用于 setget,但一旦您尝试声明 forEach 或迭代器,就会崩溃。

    【讨论】:

      猜你喜欢
      • 2019-07-01
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 2018-12-27
      相关资源
      最近更新 更多