Ricerca nel sito web

angularjs - Come calcolare una proprietà su una classe in typescript?


In JavaScript lo avrei fatto in questo modo:

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}

Ma non sono riuscito a trovare alcun modo per farlo in TypeScript. Niente di tutto questo funziona:

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")};
}

Lo inizializzo così:

somevar: A = {
    foo: 1,
    bar: 2
}

Ho provato anche questo:

somevar: A = {
    foo: 1,
    bar: 2,
    this.yep: this.foo + this.bar
}

Grazie per il tuo aiuto. Questa matematica sarà più difficile e ne avrò bisogno più di una volta, quindi non voglio metterla nel modello.

Risposta n. 1

L'esempio della classe TS con una proprietà calcolata:

class Person {
    firstName: string;
    lastName: string;
    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

L'esempio che utilizza il getter:

class Person {
    firstName: string;
    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

Risposta n. 2

A è una classe e non un interfaccia, quindi devi creare un'istanza. Non puoi semplicemente assegnare un oggetto letterale. Non basta che la 'forma' sia compatibile; deve essere un'istanza della classe.

Le variabili dichiarate con private, protected o public nel constructor saranno aggiunte alla classe.

Per esempio:

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);