The default values ​​for optional parameters in the options argument

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

Is there a better / more idiomatic way to do 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; } } 
+5
source share
3 answers

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

In addition, what you do is actually quite smart, and this is the best you can do. Such things will not work:

 constructor (options: {color: number, numberOfWheels?: number} = {color: options.color}) 
+4
source

You can use destructuring for this:

 class Car { color: number; numberOfWheels: number; constructor ({color, numberOfWheels = 4}: {color: number, numberOfWheels?: number}) { this.color = color; this.numberOfWheels = numberOfWheels; } } 

On the other hand...

 constructor (options: {color: number, numberOfWheels?: number}) { let {color, numberOfWheels = 4} = options; this.color = color; this.numberOfWheels = numberOfWheels; } 
+2
source

I have been using Typescript the latest and stable version since June 2017 with VSCode.

We can get the optional parameter and default value using the estimate below.

 export class Searcher { createLog(message: string = "Default: No Message!") { console.log(message); } } 

A good reference link to learn about optional and default values ​​in TypeScript .

Hope this helps!

-1
source

Source: https://habr.com/ru/post/1240533/


All Articles