Override method

2 snippets across 2 stacks — JavaScript, TypeScript

JSJavaScript

Inheritance (extends)

JS · Classes & OOP
syntax
class Child extends Parent {
  constructor(params) {
    super(parentParams);
  }
}
example
class Shape {
  constructor(color) {
    this.color = color;
  }
  describe() {
    return `A ${this.color} shape`;
  }
}

class Circle extends Shape {
  constructor(color, radius) {
    super(color);
    this.radius = radius;
  }
  get area() {
    return Math.PI * this.radius ** 2;
  }
  describe() {
    return `A ${this.color} circle (r=${this.radius})`;
  }
}

const c = new Circle("blue", 5);
console.log(c.describe());
console.log(c.area.toFixed(2));
output
"A blue circle (r=5)"
"78.54"

Note super() must be called in the child constructor before accessing this. Methods can be overridden. Use super.method() to call the parent version.

TSTypeScript

override Keyword

TS · Classes
syntax
class Child extends Parent {
  override method(): Type { ... }
}
example
class Transport {
  getSpeed(): number {
    return 0;
  }

  describe(): string {
    return `Speed: ${this.getSpeed()} km/h`;
  }
}

class Train extends Transport {
  override getSpeed(): number {
    return 300;
  }

  // override getSped(): number { // Error with noImplicitOverride:
  //   return 300;                 // 'getSped' does not exist on base
  // }
}
output
// override keyword verifies the method actually exists on the parent class

Note Enable noImplicitOverride in tsconfig to require the override keyword on all overriding methods. This catches typos (overriding a method that does not exist on the parent) and refactoring bugs (parent method was renamed but child was not updated).