Skip to content
Advertisement

Overriding super method in TypeScript

I’m trying to overload/override a class method in TypeScript, where the superior method takes zero arguments and the subordinate method takes one.

My TypeScript code is similar to the following:

class Super {
  create(): void {}
}

class Sub extends Super {
  create(arg: object): void {}
}

const sub = new Sub();
sub.create({});

This code produces the following error:

Property 'create' in type 'Sub' is not assignable to the same property in base type 'Super'.
  Type '(arg: object) => void' is not assignable to type '() => void'. ts(2416)

Why doesn’t this work? It it because the transpiled JavaScript output simply isn’t capable of making an inheritance distinction between these two classes? How would I accomplish something like this?

Advertisement

Answer

In TypeScript, the type of a subclass must be assignable to the type of its parent class. This allows polymorphism to work:

let sub: Sub = new Sub();
// polymorphism: we can treat a Sub as a Super
let parent: Super = sub; 

However, your code is not valid because in the situation above, we would be allowed to call parent.create() with no arguments; however, the code that actually runs is Sub.create which requires by contract that arg is present.

In summary: all members of the child’s type must be assignable to the corresponding members of the parent’s type. (arg: any) => void is not assignable to () => void.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement