感谢WebStorm,我一遍又一遍地得到以下错误:
Error:(6, 9) TS2322:Type 'AnotherRandomClass' is not assignable to type 'A'.
有人知道为什么吗?脚本仍在编译和执行,没有任何错误,但WebStorm不断抛出这个特定的错误。
AnotherRandomClass.ts
import * as Events from "events";
export default class AnotherRandomClass extends Events.EventEmitter {
static instance: AnotherRandomClass;
constructor() {
super();
AnotherRandomClass.instance = this;
}
public static getInstance(): AnotherRandomClass {
return AnotherRandomClass.instance;
}
}
RandomListener.ts
import * as Events from "events";
import AnotherRandomClass from "./AnotherRandomClass";
export default class RandomListener {
public getBaseClass<A extends Events.EventEmitter>(): A {
return AnotherRandomClass.getInstance();
}
}
tests.ts
import AnotherRandomClass from "./AnotherRandomClass"
import RandomListener from "./RandomListener";
import * as Events from "events";
new AnotherRandomClass();
console.log(AnotherRandomClass.getInstance() instanceof Events.EventEmitter);
console.log(new RandomListener().getBaseClass());
测试结果
λ node tests.js
true
AnotherRandomClass {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined }
答案 0 :(得分:0)
当您不必使用泛型时。当你说类型A扩展Events.EventEmitter A可以是任意数量的类型。作为通用参数,您可以将任何内容传递给该方法。您可以删除Type参数,只需说getInstance返回Events.EventEmitter。
class Base { }
class Sub extends Base {
static instance = new Sub();
}
class Getter {
static getClass<T extends Base>():T {
//error Sub.instance is of type Base but not necessarily T
return Sub.instance
}
static getNonGeneric(): Base {
return Sub.instance
}
}