79

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?

0

2 Answers 2

115

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") {}
}
Sign up to request clarification or add additional context in comments.

3 Comments

private foo = "foo", private bar = "bar" I guess the type can be inferred here.
in my own personal preference I liketo always type define even when it's obvious
How do you do this with destructured parameters, as succintly as possible, without duplicating the list of destructured fields?
8

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;
   }
}

4 Comments

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'.
Don't agree with comment that variables with default parameter "should be optional by default". Default parameters are to provide a default value to a variable being passed into a function. A variable that is optional does NOT need to have a default value.
@BurhanAli inside constructor this.foo = foo!; this.bar = bar!; will fix this
doing that is not type safe, the caller can provide a value of undefined and you assert it away. An optional parameter with ? is not the same as providing a default

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.