2017-01-13 1 views
0

В 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 
} 

Спасибо за вашу помощь. Эта математика будет сложнее, и я буду нуждаться в ней более одного раза, поэтому я не хочу помещать ее в шаблон.

ответ

2

Aclass, а не 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); 
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); 
+1

насчет '' this.foo' и this.bar'? Они будут неопределенными. – cartant

+0

жаль, что здесь поздно, но отсюда концепция проста, я ее отредактировал – Kaddath

0

Пример 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 
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(); 
Смежные вопросы