E 'possibile utilizzare getter / setter nella definizione di interfaccia?

voti
50

Al momento, TypeScriptnon consente l'uso get / set metodi di accesso () nelle interfacce. Per esempio:

interface I {
      get name():string;
}

class C implements I {
      get name():string {
          return null;
      } 
}

Inoltre, dattiloscritto non consente Espressione uso Array funzione in metodi di classe: per es .:

class C {
    private _name:string;

    get name():string => this._name;
}

C'è un altro modo per utilizzare un getter e setter su una definizione di interfaccia?

È pubblicato 11/10/2012 alle 12:15
fonte dall'utente
In altre lingue...                            


4 risposte

voti
68

È possibile specificare la proprietà sull'interfaccia, ma non è possibile far valere se getter e setter vengono utilizzati, in questo modo:

interface IExample {
    Name: string;
}

class Example implements IExample {
    private _name: string = "Bob";

    public get Name() {
        return this._name;
    }

    public set Name(value) {
        this._name = value;
    }
}

var example = new Example();
alert(example.Name);

In questo esempio, l'interfaccia non forza la classe di utilizzare getter e setter, avrei potuto usare una proprietà invece (esempio qui sotto) - ma l'interfaccia dovrebbe nascondere questi dettagli di implementazione in ogni caso in quanto è una promessa al codice chiamante su ciò che si può chiamare.

interface IExample {
    Name: string;
}

class Example implements IExample {
    // this satisfies the interface just the same
    public Name: string = "Bob";
}

var example = new Example();
alert(example.Name);

E, infine, =>non è consentito per i metodi della classe - si potrebbe iniziare una discussione su CodePlex , se pensate che ci sia un caso d'uso di masterizzazione per esso. Ecco un esempio:

class Test {
    // Yes
    getName = () => 'Steve';

    // No
    getName() => 'Steve';

    // No
    get name() => 'Steve';
}
Risposto il 11/10/2012 a 13:03
fonte dall'utente

voti
16

Per integrare le altre risposte, se il vostro desiderio è quello di definire un get valuesu un'interfaccia, si può fare questo:

interface Foo {
  readonly value: number;
}

let foo: Foo = { value: 10 };

foo.value = 20; //error

class Bar implements Foo {
  get value() {
    return 10;
  }
}

ma per quanto io sappia, e come altri citati, non c'è modo al momento di definire un insieme di proprietà, solo nell'interfaccia. È possibile, tuttavia, spostare la limitazione ad un errore di run-time (utile durante il ciclo di sviluppo unica):

interface Foo {
  /* Set Only! */
  value: number;
}

class Bar implements Foo {
  _value:number;
  set value(value: number) {
    this._value = value;
  }
  get value() {
    throw Error("Not Supported Exception");
  }
}

Non consigliato pratica ; ma un'opzione.

Risposto il 13/12/2016 a 11:32
fonte dall'utente

voti
2

Prima di tutto, Carattere tipografico supporta solo gete setsintassi quando rivolte a ECMAScript 5. Per raggiungere questo obiettivo, è necessario chiamare il compilatore con

tsc --target ES5

Le interfacce non supportano getter e setter. Per ottenere il codice per compilare si dovrebbe cambiare a

interface I { 
    getName():string;
}

class C implements I { 
    getName():string {
          return null;
    }   
}

Che cosa fa dattiloscritto di supporto è una sintassi speciale per i campi nei costruttori. Nel tuo caso, si potrebbe avere

interface I {
    getName():string;
}

class C implements I {
    constructor(public name: string) {
    }
    getName():string {
        return name;
    }
}

Notate come classe Cnon specifica il campo name. In realtà è dichiarato utilizzando zucchero sintattico public name: stringnel costruttore.

Come Sohnee sottolinea, l'interfaccia è in realtà dovrebbe nascondere eventuali dettagli di implementazione. Nel mio esempio, ho scelto l'interfaccia di richiedere un metodo getter java-stile. Tuttavia, è possibile anche una proprietà e poi lasciare che la classe a decidere come implementare l'interfaccia.

Risposto il 11/10/2012 a 12:45
fonte dall'utente

voti
0

Utilizzando dattiloscritto 3.4:

interface IPart {
    getQuantity(): number;
}

class Part implements IPart {
    private quantity: number;
    constructor(quantity: number) {
        this.quantity = quantity;
    }
    public getQuantity = (): number => {
        return this.quantity;
    };
}

let part = new Part(42);

// When used in typescript, quantity is not accessible.
// However, when compiled to javascript it will log '42'.
console.log(part.quantity);

// Logs '42'.
console.log(part.getQuantity());

Vedere l'esempio sul dattiloscritto Playground .

Risposto il 25/05/2019 a 17:30
fonte dall'utente

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more