我是TypeScript的新手。
为什么我收到此错误消息?
我不打算初始化抽象类。 我打算在validatorMap字典中初始化一个IsEmptyValidator的具体类。
TS2511:无法创建抽象类的实例' Validator'
interface Dictionary<T> {
[key: string]: T;
}
abstract class Validator {
constructor() {
console.log("super");
}
}
class IsEmptyValidator extends Validator {
public validate() {}
constructor(){
super();
console.log("isEmpty");
}
}
class ValidatorFactory {
private validatorMap: Dictionary<Validator> = {
"isEmpty": IsEmptyValidator
};
constructor() { }
public create(validatorType: string) {
let validatorToCreate: Validator = new this.validatorMap[validatorType];
return validatorToCreate;
}
}
答案 0 :(得分:3)
你的词典没有实例Validator
但是它的类,所以你应该这样做:
type ValidatorConstructor = {
new (): Validator;
}
class ValidatorFactory {
private validatorMap: Dictionary<ValidatorConstructor> = {
"isEmpty": IsEmptyValidator
};
constructor() {}
public create(validatorType: string) {
let validatorToCreate: Validator = new this.validatorMap[validatorType]();
return validatorToCreate;
}
}