TS2511: Unable to instantiate abstract class 'Validator'

I am new to TypeScript.

How can I get this error message?

I have no intention of initializing an abstract class. I intend to initialize the concrete class IsEmptyValidator in the validatorMap dictionary.

TS2511: Unable to instantiate 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;
    }
}

      

+3


source to share


1 answer


There are no instances in your dictionary Validator

, but its classes, so you have to 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;
    }
}

      

+2


source







All Articles