Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define optional constructor arguments with defaults in Typescript

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?

like image 729
Jeanluca Scaljeri Avatar asked Apr 10 '17 14:04

Jeanluca Scaljeri


People also ask

How do you give a default value in optional parameters in TypeScript?

Use default parameter syntax parameter:=defaultValue if you want to set the default initialized value for the parameter. Default parameters are optional. To use the default initialized value of a parameter, you omit the argument when calling the function or pass the undefined into the function.

How do you make a constructor parameter optional in TypeScript?

Like any object-oriented language, you can have an optional argument in a constructor in TypeScript also. The ? keyword is used in the argument to make it optional for the constructor. All the optional arguments of a constructor should be placed after all the mandatory arguments only in a constructor.

How do I pass a default value in TypeScript?

To set a default value for a function parameter, use an equal sign right after the parameter name, e.g. function multiply(num: number, by = 10) {} . If a value for the parameter is not provided, the argument will be replaced with the default value.

Can Constructors have optional arguments?

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.


2 Answers

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") {} } 
like image 81
Nitzan Tomer Avatar answered Sep 20 '22 16:09

Nitzan Tomer


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;    } } 
like image 33
csandreas1 Avatar answered Sep 22 '22 16:09

csandreas1