Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is not ngOnInit in Angular private?

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?

like image 307
DonkeyBanana Avatar asked Nov 05 '17 16:11

DonkeyBanana


2 Answers

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.

like image 179
Günter Zöchbauer Avatar answered Oct 04 '22 05:10

Günter Zöchbauer


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.

Contextual Type Inference

So in short, TypeScript wants to save you having to repeat unnecessary annotations.

Return Type Compatibility

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:

Return type checking

like image 41
Fenton Avatar answered Oct 04 '22 05:10

Fenton