不确定“ discriminator”在这里是否正确。 考虑以下代码:
abstract class A {
}
class A1 extends A {
}
class A2 extends A {
}
interface SomeMap {
[key: string]: new (...args: any[]) => A;
}
class B<T extends SomeMap> {
public test<K extends keyof T>(key: K, instance: InstanceType<T[K]>): void {}
}
const map = {
a1: A1,
a2: A2,
};
class C extends B<typeof map> {}
const c = new C();
c.test('a1', new A1()); // No errors from TS - good
c.test('a1', new A2()); // No errors from TS - bad, I want ts to error here!
并带有“鉴别符”:
abstract class A {
protected abstract discriminator: undefined;
}
class A1 extends A {
protected discriminator: undefined;
}
class A2 extends A {
protected discriminator: undefined;
}
interface SomeMap {
[key: string]: new (...args: any[]) => A;
}
class B<T extends SomeMap> {
public test<K extends keyof T>(key: K, instance: InstanceType<T[K]>): void {}
}
const map = {
a1: A1,
a2: A2,
};
class C extends B<typeof map> {}
const c = new C();
c.test('a1', new A1()); // No errors from TS - good
c.test('a1', new A2()); // TS error - good!
在避免从A继承的类中声明“ discriminator”道具的同时,有什么方法可以使其起作用?只是想在TS中检测到A1!= A2。