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).

Frequently asked questions

How does JavaScript handle override method?
This task is covered in 2 stacks on this page: JavaScript, TypeScript. The "Inheritance (extends)" snippet in JavaScript uses `class Child extends Parent {`.
Which code does the JavaScript example use?
The "Inheritance (extends)" snippet uses `class Child extends Parent {`, from the Classes & OOP section of the JavaScript cheat sheet.
Which stacks cover "override method" on this page?
JavaScript, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Inheritance (extends)": super() must be called in the child constructor before accessing this. Methods can be overridden. Use super.method() to call the parent version.