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;
}
}
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.
OptionalAttribute parameters do not require a default value.
A parameter with a default value, is often known as an "optional parameter".
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.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With