0
0
Typescriptprogramming~5 mins

Super keyword behavior in Typescript

Choose your learning style9 modes available
Introduction

The super keyword helps you use or extend features from a parent class inside a child class.

When you want a child class to use or add to a method from its parent class.
When you need to call the parent class constructor to set up inherited properties.
When overriding a method but still want to keep the original behavior from the parent.
When you want to reuse code from the parent class without rewriting it.
Syntax
Typescript
class Parent {
  constructor() {}
  method() {}
}

class Child extends Parent {
  constructor() {
    super();
  }
  method() {
    super.method();
  }
}

super() must be called in the child constructor before using this.

You can use super.methodName() to call a specific method from the parent.

Examples
Calls the parent constructor to print the animal name before printing dog creation.
Typescript
class Animal {
  constructor(name: string) {
    console.log(`Animal created: ${name}`);
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name);
    console.log('Dog created');
  }
}
Calls the parent greet method, then adds extra greeting.
Typescript
class Person {
  greet() {
    console.log('Hello from Person');
  }
}

class Student extends Person {
  greet() {
    super.greet();
    console.log('Hello from Student');
  }
}
Sample Program

This program shows how super calls the parent constructor and method, then the child adds its own message.

Typescript
class Vehicle {
  constructor(public brand: string) {}
  start() {
    console.log(`${this.brand} vehicle started.`);
  }
}

class Car extends Vehicle {
  constructor(brand: string, public model: string) {
    super(brand);
  }
  start() {
    super.start();
    console.log(`${this.model} car is ready to go!`);
  }
}

const myCar = new Car('Toyota', 'Corolla');
myCar.start();
OutputSuccess
Important Notes

Always call super() first in the child constructor before using this.

You can use super to access parent methods even if you override them in the child.

Summary

super lets child classes use or extend parent class features.

Use super() in constructors to call the parent constructor.

Use super.method() to call a parent method inside an overridden method.