Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values for optional parameters in options argument

Tags:

typescript

I want to pass an object as argument for the constructor of a class. Some keys of the options object are optional.

Is there a better / more idiomatic way of accomplishing the following in typescript? Thanks

class Car {
    color: number;
    numberOfWheels: number;

    constructor (options: {color: number, numberOfWheels?: number}) {
        options.numberOfWheels |= 4;

        this.color = options.color;
        this.numberOfWheels = options.numberOfWheels;
    }
}
like image 513
pistacchio Avatar asked Jan 13 '16 13:01

pistacchio


People also ask

What are default and optional parameters?

The default value of an optional parameter is a constant expression. The optional parameters are always defined at the end of the parameter list. Or in other words, the last parameter of the method, constructor, etc. is the optional parameter.

Is it mandatory to specify a default value to optional parameter?

OptionalAttribute parameters do not require a default value.

What are the parameters that are default values *?

A parameter with a default value, is often known as an "optional parameter".

How do you indicate optional arguments?

To indicate optional arguments, Square brackets are commonly used, and can also be used to group parameters that must be specified together. To indicate required arguments, Angled brackets are commonly used, following the same grouping conventions as square brackets.


1 Answers

Use if (options.numberOfWheels === void 0) { options.numberOfWheels = 4; } instead. (Otherwise 0 or NaN ... will be 4 as well)

Aside that what you do is actually pretty clever and it's the best you can do. Things like that won't work:

constructor (options: {color: number, numberOfWheels?: number} = {color: options.color})
like image 180
CoderPi Avatar answered Oct 16 '22 05:10

CoderPi