You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: book-content/chapters/08-classes.md
+59Lines changed: 59 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -437,6 +437,65 @@ class Album {
437
437
438
438
Now, the `title` property can be accessed from within the `SpecialEditionAlbum` class, and not from outside the class.
439
439
440
+
### Safe Overrides With `override`
441
+
442
+
You can run into trouble when extending classes if you try to override a method in a subclass. Let's say our `Album` class implements a `displayInfo` method:
443
+
444
+
```typescript
445
+
classAlbum {
446
+
// ...
447
+
displayInfo() {
448
+
console.log(
449
+
`${this.title} by ${this.artist}, released in ${this.releaseYear}.`,
450
+
);
451
+
}
452
+
}
453
+
```
454
+
455
+
And our `SpecialEditionAlbum` class also implements a `displayInfo` method:
456
+
457
+
```typescript
458
+
classSpecialEditionAlbumextendsAlbum {
459
+
// ...
460
+
displayInfo() {
461
+
console.log(
462
+
`${this.title} by ${this.artist}, released in ${this.releaseYear}.`,
This overrides the `displayInfo` method from the `Album` class, adding an extra log for the bonus tracks.
470
+
471
+
But what happens if we change the `displayInfo` method in `Album` to `displayAlbumInfo`? `SpecialEditionAlbum` won't automatically get updated, and its override will no longer work.
472
+
473
+
To prevent this, you can use the `override` keyword in the subclass to indicate that you're intentionally overriding a method from the parent class:
474
+
475
+
```typescript
476
+
classSpecialEditionAlbumextendsAlbum {
477
+
// ...
478
+
override displayInfo() {
479
+
console.log(
480
+
`${this.title} by ${this.artist}, released in ${this.releaseYear}.`,
Now, if the `displayInfo` method in the `Album` class is changed, TypeScript will give an error in the `SpecialEditionAlbum` class, letting you know that the method is no longer being overridden.
488
+
489
+
You can also enforce this by setting `noImplicitOverride` to `true` in your `tsconfig.json` file. This will force you to always specify `override` when you're overriding a method:
490
+
491
+
```json
492
+
{
493
+
"compilerOptions": {
494
+
"noImplicitOverride": true
495
+
}
496
+
}
497
+
```
498
+
440
499
### The `implements` Keyword
441
500
442
501
There are some situations where you want to enforce that a class adheres to a specific structure. To do that, you can use the `implements` keyword.
0 commit comments