I'm checking the code samples and even the docs getting nothing av information. Then, I google for a while and still nothing.
Why do we type
ngOnInit() { ... }
instead of
private ngOnInit() { ... }
or, for that matter, as long as I'm whining on the subject
private ngOnInit() : void { ... }
to embrace the full power of TypeScript?
edit
Based on the comments I need to extend the question. Why don't we write:
public ngOnInit() : void { ... }
instead?
The method is called from Angular. If it were private, it couldn't be called from outside.
The returned value is ignored by Angular, therefore the return type doesn't matter.
Based on the comments I need to extend the question. Why don't we write:
public ngOnInit() : void { ... }
instead?
TypeScript is able to provide contextual type information, so when you are implementing an interface, you don't need to repeat types from the interface.
For example, if you consider the following shortened example:
interface OnInit {
ngOnInit(): void
}
const example: OnInit = {
ngOnInit: function () { }
}
If you hover over ngOnInit
you'll see the return type is already void, because it has inferred the return type for you contextually.
So in short, TypeScript wants to save you having to repeat unnecessary annotations.
There is one case that might make you consider adding the return type annotation. With no annotation, the following is allowed:
const x: OnInit = {
ngOnInit: function () {
return 4;
}
}
In the specific case of the OnInit
interface, this won't cause any problems as the return type is ignored. However, if you wanted to be told that your return type doesn't look right, the annotation would give you that additional information:
interface OnInit {
ngOnInit(): void
}
const x: OnInit = {
ngOnInit: function (): void {
return 4;
}
}
Like this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With