72

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?

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333

2 Answers2

110

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") {}
}
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • 1
    `private foo = "foo", private bar = "bar"` I guess the type can be inferred here. – Andre Elrico Jun 14 '19 at 11:32
  • 5
    in my own personal preference I liketo always type define even when it's obvious – Derek Lawrence Oct 09 '19 at 16:53
  • 3
    How do you do this with destructured parameters, as succintly as possible, without [duplicating the list of destructured fields](https://stackoverflow.com/questions/23314806/setting-default-value-for-typescript-object-passed-as-argument/32596200#32596200)? – Dan Dascalescu Mar 04 '20 at 02:42
6

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;
   }
}
csandreas1
  • 2,026
  • 1
  • 26
  • 48
  • Unclear if this worked at the time, but now compilation fails with this error: `error TS2322: Type 'string | undefined' is not assignable to type 'string'.` – Burhan Ali Jul 11 '23 at 19:56