Typescript allows parameter properties
class ParameterProperty {
constructor(private member: number) {}
}
The above creates a class with
What about:
class Destructed {
private prefix: string;
private suffix: string;
constructor(opts: DestructedOptions) {
Object.assign(this, opts);
}
}
Also, there's an open issue on this: Combining destructuring with parameter properties
If you want to avoid re-writing the properties in the class then you'll need to make the members public, when that's the case then the solution is as shown in the issue I linked to:
class Destructed {
constructor(opts: DestructedOptions) {
Object.assign(this, opts);
}
}
interface Destructed extends DestructedOptions { }
let destructed = new Destructed({ prefix: "prefix", suffix: "suffix" });
console.log(destructed.prefix);
console.log(destructed.suffix);
console.log(destructed.DoesntExist); // error
(code in playground)
In ECMAScript, destructuring assignment results in variables in variables (not properties than properties) receiving the component values.
There has been a TypeScript feature request/suggestion for combining destructuring with parameter properties open since October of 2015. That would probably be the most effective place to track the status of whatyou want.
There's no obvious, direct way to do what you want. Consider holding options
in your class instead of individual properties, as in
interface DestructedOptions {
prefix: string;
suffix: string;
}
class Destructed {
constructor(public options: DestructedOptions) {}
}
<!-- in template -->
Prefix is {{options.prefix}}!!