Issue
In javascript I would have done it like this:
function a(b,c) {this.foo = b; this.bar = c; this.yep = b+c}
// undefined
b = new a(1,2)
// a {foo: 1, bar: 2, yep: 3}
But I haven't been able to find any way to do it in typescript. None of this works:
class A {
foo: number;
bar: number;
yep: foo + bar;
}
class A {
foo: number;
bar: number;
yep: this.foo + this.bar;
}
class A {
foo: number;
bar: number;
let yep:number = this.foo + this.bar;
}
class A {
foo: number;
bar: number;
yep: number;
constructor() {
this.yep = this.foo + this.bar;
}
}
class A {
foo: number;
bar: number;
get yep(): number {
return this.foo + this.bar;
}
}
class A {
foo: number;
bar: number;
yep: function () {return this.get("foo") + this.get("bar")};
}
I initialize it like this:
somevar: A = {
foo: 1,
bar: 2
}
Also I tried this:
somevar: A = {
foo: 1,
bar: 2,
this.yep: this.foo + this.bar
}
Thank you for your help. This math will have be more difficult and I'll need it more than once, so I don't want to put it in the template.
Solution
A is a class and not an interface, so you need to construct an instance. You cannot simply assign an object literal. It's not enough for the 'shape' to be compatible; it must be an instance of the class.
Variables declared with private, protected or public in the constructor will be added to the class.
For example:
class A {
public yep: number;
constructor(
public foo: number, // will be transpiled in the constructor to: this.foo = foo;
public bar: number // will be transpiled in the constructor to: this.bar = bar;
) {
this.yep = foo + bar;
}
}
const a: A = new A(1, 2);
Answered By - cartant
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.