Reputation: 1710
My class looks like this...
class MyClass {
c: number;
avg: number;
diam: number;
constructor(a: number, b: number) {
this.c = Math.sqrt(a * a + b * b);
this.avg = (a + b) / 2;
this.diam = Math.abs(b - a);
}
}
... but actually has more members that need declaring and initialising from the constructor arguments. I want to avoid the boilerplate of declaring the members outside the constructor and inside the constructor. Is there anyway to do that?
Upvotes: 0
Views: 424
Reputation: 33101
You can do smth like that:
interface MathData {
c: number;
avg: number;
diam: number;
}
const builder = (a: number, b: number):MathData => ({
c: Math.sqrt(a * a + b * b),
avg: (a + b) / 2,
diam: Math.abs(b - a),
})
class MyClass {
constructor(a: number, b: number) {
Object.assign(this, builder(a, b));
}
calc(this: MathData) {
this.avg // ok
this.c // ok
this.diam // ok
}
}
Please, be aware that TypeScript does not track mutations.Hence, in order to get c
or avg
or diam
you need to explicitly type this
parameter.
Playground
Upvotes: 1
Reputation: 8718
Yes, TypeScript supports something like that:
class MyClass {
c: number = Math.sqrt(this.a * this.a + this.b * this.b);
avg: number = (this.a + this.b) / 2;
diam: number = Math.abs(this.b - this.a);
constructor(public a: number, private readonly b: number) {
}
}
That'll create a public field a
and a private read-only field b
. These are created before the initializers for the regular fields are executed, thus you can access those too.
Upvotes: 1