TS2511: Cannot create an instance of the abstract class 'Validator'

javascript, typescript, typescript2.0

Solution

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;
    }
}

Problem

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; } } ```

Original source