简体   繁体   中英

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?

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.

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:

返回类型检查

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM