How to define optional constructor arguments with defaults in Typescript

JavascriptTypescript

Javascript Problem Overview


Is it possible to have optional constructor arguments with default value, like this

export class Test {
    constructor(private foo?: string="foo", private bar?: string="bar") {}
}

This gives me the following error:

Parameter cannot have question mark and initializer.

I would like to create instances like

x = new Test();               // x.foo === 'foo'            
x = new Test('foo1');         // x.foo === 'foo1'
x = new Test('foo1', 'bar1');

What is the correct typescript way to achieve this?

Javascript Solutions


Solution 1 - Javascript

An argument which has a default value is optional by definition, as stated in the docs:

> Default-initialized parameters that come after all required parameters > are treated as optional, and just like optional parameters, can be > omitted when calling their respective function

It's the same for constructors as it is for other functions, so in your case:

export class Test {
    constructor(private foo: string = "foo", private bar: string = "bar") {}
}

Solution 2 - Javascript

You can add question mark after your args, which is cleaner. If you add default parameters, it should be optional by default.

export class Test {
   foo: string; 
   bar: string;

    constructor(foo?: string, bar?: string) {
    this.foo = foo;
    this.bar = bar;
   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeanluca ScaljeriView Question on Stackoverflow
Solution 1 - JavascriptNitzan TomerView Answer on Stackoverflow
Solution 2 - Javascriptcsandreas1View Answer on Stackoverflow