To make constructor calls more readable, I generally prefer to use named parameters as follows:
class MyClass {
constructor(private args: {a: number, b: string, c: boolean}) {}
}
// Example constructor call:
const x = new MyClass({a: 1, b: "hello", c: true})
However, I also want a, b, and c to be publicly readable, i.e. I'd like to be able to call x.a, x.b and x.c rather than using x.args.a, x.args.b, and x.args.c. I can come up with a few different ways of doing this (see below), but they all involve repetitive boilerplate to explicitly create properties or getters.
Is there a way that I can create these getters automatically, e.g. by writing a decorator or using a generic?
Approach 1: explicitly declare properties and populate them in the constructor
This is pretty verbose!
class MyClass1 {
a: number;
b: string;
c: boolean;
constructor(private args: {a: number, b: string, c: boolean}) {
this.a = args.a;
this.b = args.b;
this.c = args.c;
}
}
Approach 2: store args and write getters
More concise than Approach 1, but I'd love to have these getters created automatically.
class MyClass2 {
constructor(private args: {a: number, b: string, c: boolean}) {};
get a(): number {return this.args.a}
get b(): string {return this.args.b}
get c(): boolean {return this.args.c}
}