You can use Object destructuring introduced in ES6 to archieve the desired behavior: reference. TypeScript is able to transpile this feature for usage with ES5 to target older browsers. However, as of ES6, this is also perfectly valid JavaScript.
Basically, it looks like this: constructor({ year, month, day})
and is invoked, for instance, as new Bar({ year: 2017 })
. Then you can access year
as a variable within the constructor, e.g. for assigning this.year = year
.
More interesting than that is the usage with default values, e.g.
constructor({ year = new Date().getFullYear(),
month = new Date().getMonth(),
day = new Date().getDay()
} = {})
which allows invoking the constructor with 0, 1, 2 or 3 parameters respectively (see snippet below).
The somewhat cryptic = {}
is for the case when you create a new instance without any parameters. First, {}
is used as the default value for the parameter object. Then, since year
is missing, the default value for that one is added, then for month and for day respectively.
For usage with TypeScript, you can, of course, add additional typings,
constructor({ year = new Date().getFullYear(),
month = new Date().getMonth(),
day = new Date().getDay()
}: { year?: number, month?: number, day?: number } = {}) {
...
}
Although this really looks cryptic.
class Bar {
constructor({ year, month, day }) {
this.year = year;
this.month = month;
this.day = day;
}
log () {
console.log(`year: ${this.year}, month: ${this.month}, day: ${this.day}`);
}
}
new Bar({ day: 2017 }).log();
class Foo {
constructor({ year = new Date().getFullYear(),
month = new Date().getMonth(),
day = new Date().getDay()
} = {}) {
this.year = year;
this.month = month;
this.day = day;
}
log () {
console.log(`year: ${this.year}, month: ${this.month}, day: ${this.day}`);
}
}
console.log('with default value:');
new Foo().log();
new Foo({ day: 2 }).log();
new Foo({ day: 2, month: 8 }).log();
new Foo({ year: 2015 }).log();