DEV Community

Cover image for Understanding This and Super in Typescript
Taki
Taki

Posted on • Edited on

Understanding This and Super in Typescript

In Typescript, this and super are keywords used in object-oriented programming to refer to the current instance of a class and the base class, respectively.


This keyword

Definition: Refers to the current instance of the class.
Use Case:

  • Access instance properties and methods.
  • Call another method within the same class.
  • Pass the current object as an argument
class Pizza {
    name: string

    constructor(name: string){
        this.name = name;
    }

    cook():void{
        console.log(`Start cooking ${this.name} pizza`)
    }
}

const pepperoniPizza = new Pizza("pepperoni");
pepperoniPizza.cook();

Enter fullscreen mode Exit fullscreen mode

Image description

super keyword

  • Definition: Refers to the base class (the parent class) of the current class.
  • Use Cases:
    • Call the constructor of the base class.
    • Access methods and properties from the base class

Example:

class Animal {
    name: string;

    constructor(name: string) {
      this.name = name;
    }

    makeSound(): void {
      console.log(`${this.name} makes a sound.`);
    }
  }

  class Dog extends Animal {
    constructor(name: string) {
      super(name); // Calls the constructor of the base class
    }

    makeSound(): void {
      super.makeSound(); // Calls the base class method
      console.log(`${this.name} barks.`);
    }
  }

  const dog = new Dog("Buddy");
  dog.makeSound();
Enter fullscreen mode Exit fullscreen mode

and the output include: makeSound() of Base Class is Animal and makeSound of subclass is Dog like this:

Buddy makes a sound.
Buddy barks.
Enter fullscreen mode Exit fullscreen mode

Image description


Key Points:

1. this:

  • Alway refers to the current instance
  • Can be used in constructor, method, or arrow functions.
  • In arrow functions, this is lexically bound to the surrounding context.

2. super:

  • Can only be used in classes that extend another class.
  • Must be called in the constructor before accessing this in a derived class.
  • Can be used to call parent class methods.
class Parent {
  protected message: string = "Hello from Parent!";
}

class Child extends Parent {
  showMessage(): void {
    console.log(super.message); // Accesses the parent class property
  }
}

const child = new Child();
child.showMessage(); // Output: Hello from Parent!

Enter fullscreen mode Exit fullscreen mode

By using this and super correctly, you can manage inheritance and object behavior effectively in Typescript.

Top comments (0)