Kamal Aslam
Kamal Aslam

Reputation: 38

Method overriding in Angular2

I have two components, one is parent and the other is child. Child extends from Parent. Parent has a method open(). Child overloads open() by rewriting and adding a parameter. It results in an error: open() is a property, and the property types do not match across classes.

open() => void 

is not equal to

open(message: string) => void

Parent :

export class ParentClass {
    constructor() { super(); }

    open(){
        return "Hello World!";
    }
}

Child:

export class ChildClass extends ParentClass {
    constructor() { super(); }

    open(message: string){
        return message;
    }
}

Upvotes: 2

Views: 26863

Answers (2)

Arkadiusz Michowski
Arkadiusz Michowski

Reputation: 112

The reason why this code doesn't work is simple:

let parent: ParentClass = new ParentClass();
parent.open();
parent = new ChildClass();
// what happens now?
parent.open();

After the third line of code, parent is still a type of ParentClass, so open call should be valid. On the other hand, it contains a ChildClass, so we aren't providing neccessary parameter for this method: message: string. It's a paradox.

If you want this code to be valid, both methods should share the same parameters.

Two tips for you:

  1. Avoid inheritance. Seriously, most likely you don't need it and most likely it will only lead to problems, even if it doesn't seem like at first. Try: composition over inheritance.
  2. If you still want to follow this way, try this answer.

Upvotes: 3

Thierry Templier
Thierry Templier

Reputation: 202266

I think that you need the same signature for the method in the subclass:

export class ParentClass {
  constructor() { 
  }

  open(message:string){ // <-----
    return "Hello World!";
  }
}

export class ChildClass extends ParentClass {
  constructor() { super(); }

  open(message: string){
    return message;
  }
}

Or make the parameter optional in the sub class:

export class ParentClass {
  constructor() { 
  }

  open(message:string){
    return "Hello World!";
  }
}

export class ChildClass extends ParentClass {
  constructor() { super(); }

  open(message?: string){ // <-----
    return message;
  }
}

See this question:

Upvotes: 0

Related Questions