简体   繁体   中英

Passing an optional parameter with a default value in Angular2

I have the following constructor:

  constructor(@Optional() private config?: DefaultConfig) {
      this.config = config || new DefaultConfig();
  }

Is there any way to avoid doing this.config = config || new DefaultConfig(); this.config = config || new DefaultConfig(); ? What I want is to add the default value in the constructor's parameter? Something like this:

  constructor(@Optional() private config?=new DefaultConfig(): DefaultConfig) {}

Thanks!

So I'm not familiar with Angular2, however in pure TypeScript, the following achieves your intention:

constructor(private config = new DefaultConfig()) {}

That is, if no config is passed, this.config will be a new DefaultConfig . It also ensures that the constructor parameter must be of type DefaultConfig .

Did you try the following?

constructor(@Optional() private config: DefaultConfig=new DefaultConfig()) {
  ..
}

Note: no more ? before :

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