Search code examples
angulartypescriptinheritanceconstructorangular7

Typescript:error TS2377: Constructors for derived classes must contain a 'super' call


I am Trying to implement this Stackblitz example of angular-upload-file-with-progress-bar but in my code

export class UploadDocumentTemplateComponent extends FieldType {}

I have this line because of it I'm getting this error

error TS2377: Constructors for derived classes must contain a 'super' call.

how to resolve this issue?


Solution

  • To provide a bit of a more complete answer or an explanation to why you do the above answer, the word super is a reference to the super class or the parent class of UploadDocumentTemplateComponent which is FieldType.

    You don't show here if you called the constructor of the child class, but whenever you do, it's required to call the constructor method of the parent as well.

    And you do it like this:

    export class UploadDocumentTemplateComponent extends FieldType {
      constructor() {
        super();
      }
    }
    

    Again for more completions' sake. Even when you pass in super(); you might still see an error especially if you have the following:

    class FieldType {
      constructor(public color: string) {}
    }
    
    class UploadDocumentTemplateComponent extends FieldType {
      constructor() {
        super():
      }
    }
    

    At which point you resolve that like so:

    class FieldType {
      constructor(public color: string) {}
    }
    
    class UploadDocumentTemplateComponent extends FieldType {
      constructor() {
        super('red'):
      }
    }
    

    But chances are you don't want to do that, chances are we want the color to still come in as an argument to your UploadDocumentTemplateComponent when you create it.

    So maybe we can take in an argument to the UploadDocumentTemplateComponent constructor function like so:

    class FieldType {
      constructor(public color: string) {}
    }
    
    class UploadDocumentTemplateComponent extends FieldType {
      constructor(color: string) {
        super('red'):
      }
    }
    

    Now another detail to pay attention to is the access modifier, so notice in this example I did not add a public modifier. I did not put the public keyword on because we do not want to reassign or create a new field in UploadDocumentTemplateComponent of color, the field color belongs to FieldType in my example.

    That's why I did not put on the modifier of public.

    Now we call the parent class constructor with the super class here and we are not going to pass in the hard coded red, instead we can pass in the color like so:

    class FieldType {
      constructor(public color: string) {}
    }
    
    class UploadDocumentTemplateComponent extends FieldType {
      constructor(color: string) {
        super(color):
      }
    }