在javascript中,我应该这样做:
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}
但是我没有找到任何办法可以在打字稿中做到这一点。这些都不起作用:
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")};
}
我像这样初始化它:
somevar: A = {
foo: 1,
bar: 2
}
我也试过这个:
somevar: A = {
foo: 1,
bar: 2,
this.yep: this.foo + this.bar
}
感谢您的帮助。这个数学将更加困难,我将不止一次需要它,所以我不想将其放在模板中。
A
是,class
而不是interface
,因此您需要构造一个实例。您不能简单地分配对象文字。仅仅兼容“形状”还不够。它必须是该类的一个实例。
变量与声明private
,protected
或public
在constructor
将被添加到类。
例如:
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句