[Typescript 5] override keyword

Overrides

A common mistake, that has historically been difficult for TypeScript to assist with is typos when overriding a class method

class Car {
  honk() {
    console.log("beep")
  }
}

class Truck extends Car {
  hoonk() { // OOPS!
    console.log("BEEP")
  }
}

const t = new Truck();
t.honk(); // "beep"
Try

In this case, it looks like the intent was to override the base class method, but because of the typo, we defined an entirely new method with a new name. TypeScript 5 includes an override keyword that makes this easier to spot

class Car {
  honk() {
    console.log("beep")
  }
}

class Truck extends Car {
  //This member cannot have an 'override' modifier because it is not declared in the base class 'Car'. Did you mean 'honk'?(4117)
  override hoonk() { // OOPS!
    console.log("BEEP")
  }
}

const t = new Truck();
t.honk(); // "beep"

 

Sometimes, we might just forgot to add override in extended class, typescript has config option noImplicityOverride: true to help you to prevent this kind of error.

posted @ 2024-01-17 11:13  Zhentiw  阅读(10)  评论(0编辑  收藏  举报