Angular life-cycle events call without implementing interface?
In typescript, you don't need to implement explicitely an interface to implement it.
Take a look at the following piece of code :
export interface BaseModel {
int myNumber;
}
export class SomeModel {
int myNumber;
}
The following is perfectly correct :
private myFunction(myModel: BaseModel) {
// Do smthg
}
let johnDoe = new SomeModel();
myFunction(johnDoe);
Perfectly legit because type checking is not based on what class is implementing, but because all the properties of BaseModel are contained into SomeModel.
This is sometimes called “duck typing” or “structural subtyping”
https://www.typescriptlang.org/docs/handbook/interfaces.html
The use of the Angular lifecycle interfaces is optional. They just help you as a developer.
Technically, TypeScript is compiled to JavaScript, which doesn't have interfaces. Angular just calls the JavaScript Lifecycle methods if they exist. That's the reason why it doesn't make any difference if you use the interfaces or not. (Source: Docs)
Nevertheless, you should use the interfaces for multiple reasons:
- It is more clear which Lifecycle events are actually used. In big classes with many methods you quickly lose the overview. The use of the interfaces allow you to quickly determine all used Lifecycle methods in one place - at the beginning of the TypeScript Class.
- The TypeScript compiler warns you if you don't implement the Lifecycle methods correctly, for example if you forgot to implement the method, misspelled the method name or the method was accidentally removed.
(Credits to @Nick)