[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 @   Zhentiw  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-01-17 [Accessibility] Create a Human Readable Time Formatter
2023-01-17 [Typescript] Generics in a Class Names Creator
2020-01-17 [NGXS] Async Action "Fire and Forgot" && "Fire and Wait"
2019-01-17 [Functional Programming] Draw Items from One JavaScript Array to Another using a Pair ADT
2019-01-17 [TypeScript] Create Explicit and Readable Type Declarations with TypeScript mapped Type Modifiers
2018-01-17 [Transducer] Lazyness in Transduer
2018-01-17 [Transducer] Create a Sequence Helper to Transduce Without Changing Collection Types
点击右上角即可分享
微信分享提示