在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
}
感谢您的帮助。这个数学会更困难,我不止一次需要它,所以我不想把它放在模板中。
答案 0 :(得分:2)
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);
答案 1 :(得分:1)
具有计算属性的TS class示例:
class Person {
public firstName: string;
public lastName: string;
public fullName: string;
constructor (firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = firstName + ' ' + lastName;
}
}
let person = new Person('John', 'Doe');
console.log(person.fullName); // => John Doe
使用getter
的示例:
class Person {
public firstName: string;
public lastName: string;
constructor (firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
}
let person: Person = new Person('John', 'Doe');
console.log(person.fullName); // => John Doe
答案 2 :(得分:0)
如果你想在课堂上这样做:
class A {
foo: number;
bar: number;
yep: number;
constructor(a: number, b: number) {
this.foo = a;
this.bar = b;
this.yep = a + b;
}
//add getter or setter functions
}
let inst = new A(1, 2);
答案 3 :(得分:0)
试试这个,
export class A {
public foo: number;
public bar: number;
public yep: number
constructor(a: number, b: number) {
this.bar = a;
this.foo = b;
this.yep = this.bar + this.foo;
}
public get(): number {
return this.yep;
}
}
let a = new A(1, 2);
a.get();
答案 4 :(得分:0)
另一个变种。
使用Object.assign
这样做不会丢失类型安全性。
请记住,除非您专门启用strictNullChecks
(推荐),否则TypeScript将始终认为undefined | null
可分配给任何内容。
interface IA {
foo: number;
bar: number;
}
class BaseClass {
constructor(obj: IA) {
if (obj) Object.assign(this, obj);
}
}
class A extends BaseClass implements IA {
public foo: number;
public bar: number;
constructor(obj: IA) {
super(obj);
}
public get yep(): number {
return this.foo + this.bar;
}
}
const somevar: A = new A({
foo: 1,
bar: 2,
})
console.log(somevar)