After reading the feedback, I realize the need to further elaborate on the question. Why not use this syntax instead:
public ngOnInit(): void { ... }
?
TypeScript has the capability to provide type information based on context, eliminating the need to redundantly specify types from interfaces.
For instance, consider the following concise example:
interface OnInit {
ngOnInit(): void
}
const example: OnInit = {
ngOnInit: function () { }
}
When you hover over ngOnInit
, you'll notice that the return type is already inferred as void, thanks to contextual typing.
https://i.stack.imgur.com/sQXJ2.png
In summary, TypeScript aims to reduce unnecessary annotations and repetitive declarations for developers.
Ensuring Return Type Compatibility
There is a scenario where adding a return type annotation may be beneficial. Without an annotation, the following code is valid:
const x: OnInit = {
ngOnInit: function () {
return 4;
}
}
Although in the specific case of the OnInit
interface, disregarding the return type does not pose issues. However, if you wish to receive alerts about improper return types, the annotation provides additional clarity:
interface OnInit {
ngOnInit(): void
}
const x: OnInit = {
ngOnInit: function (): void {
return 4;
}
}
As shown here:
https://i.stack.imgur.com/A5W0f.png