如何对键为 类 且值为 类 的实例的映射进行类型提示?

How to type-hint a Map whose keys are classes and values are instances of those classes?

我有一个映射,其键是 类,它们的值是相应 类.

的实例
// JavaScript code
class A {};
class B {};

const map = new Map();

map.set(A, new A);
map.set(B, new B);

如何在打字稿中正确输入此地图的提示?

您需要一个自定义映射定义,因为标准映射定义要求键和值也是相同的类型,而且它不允许在两者之间设置任何关系。

所以它可能是这样的:

type Constructor = new (...args: any) => any;

interface ConstructorMap {
    clear(): void;
    delete(key: Constructor): boolean;
    get<K extends Constructor>(key: K): InstanceType<K> | undefined;
    has(key: Constructor): boolean;
    set<K extends Constructor>(key: K, value: InstanceType<K>): this;
    readonly size: number;
}

class A { a = '' };
class B { b = 1 };

const map: ConstructorMap = new Map();

map.set(A, new A);
map.set(B, new B);

const a = map.get(A) // A | undefined

// Expect error: Argument of type 'B' is not assignable to parameter of type 'A'
map.set(A, new B);

Playground

Docs InstanceType<Type> 实用程序