Skip to content

Commit f0fd9ea

Browse files
authored
Merge pull request #24 from total-typescript/matt/added-override-to-classes
Added override to classes
2 parents 4b01606 + b4edc95 commit f0fd9ea

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

book-content/chapters/08-classes.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,65 @@ class Album {
437437

438438
Now, the `title` property can be accessed from within the `SpecialEditionAlbum` class, and not from outside the class.
439439

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+
class Album {
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+
class SpecialEditionAlbum extends Album {
459+
// ...
460+
displayInfo() {
461+
console.log(
462+
`${this.title} by ${this.artist}, released in ${this.releaseYear}.`,
463+
);
464+
console.log(`Bonus tracks: ${this.bonusTracks.join(", ")}`);
465+
}
466+
}
467+
```
468+
469+
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+
class SpecialEditionAlbum extends Album {
477+
// ...
478+
override displayInfo() {
479+
console.log(
480+
`${this.title} by ${this.artist}, released in ${this.releaseYear}.`,
481+
);
482+
console.log(`Bonus tracks: ${this.bonusTracks.join(", ")}`);
483+
}
484+
}
485+
```
486+
487+
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+
440499
### The `implements` Keyword
441500

442501
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

Comments
 (0)