Reputation:
I'm new to TypeScript.
How come I get this error message?
I don't intend to initialize abstract class. I intend to initialize a concrete class that is IsEmptyValidator in validatorMap dictionary.
TS2511: Cannot create an instance of the abstract class '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;
}
}
Upvotes: 6
Views: 6955
Reputation: 164147
Your dictionary doesn't have instances Validator
but classes of it, so you should do this:
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;
}
}
Upvotes: 10