Czy jest możliwe aby użyć pobierające / ustawiające w definicji interfejsu?

głosy
50

W tej chwili TypeScriptnie pozwala na użytkowanie get / zestaw metod (dostępowych) w interfejsach. Na przykład:

interface I {
      get name():string;
}

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

Ponadto, maszynopis nie pozwala na wyrażenie funkcyjne zastosowanie w metodach klasy Array: ex .:

class C {
    private _name:string;

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

Czy istnieje inny sposób mogę użyć getter i setter na definicji interfejsu?

Utwórz 11/10/2012 o 12:15
źródło użytkownik
W innych językach...                            


4 odpowiedzi

głosy
68

Można określić właściwość na interfejsie, ale nie można wymusić, czy pobierające i ustawiające są wykorzystywane w następujący sposób:

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

W tym przykładzie, interfejs nie zmusza klasę do korzystania pobierające i ustawiające może użyłem właściwość zamiast (przykład poniżej) - ale interfejs ma ukryć te szczegóły implementacji i tak jak jest to obietnica do kodu wywołującego o tym, co można nazwać.

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

I wreszcie, =>nie jest dozwolona dla metod klasy - można rozpocząć dyskusję na temat Codeplex jeśli uważasz, że jest palenie przypadek użycia dla niego. Oto przykład:

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

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

    // No
    get name() => 'Steve';
}
Odpowiedział 11/10/2012 o 13:03
źródło użytkownik

głosy
16

Aby uzupełnić inne odpowiedzi, jeśli twoje pragnienie jest zdefiniowanie get valuena interfejsie, można to zrobić:

interface Foo {
  readonly value: number;
}

let foo: Foo = { value: 10 };

foo.value = 20; //error

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

ale o ile mi wiadomo, i jak inni już wspomniano, nie ma sposobu, aby określić aktualnie ustawioną właściwość tylko w interfejsie. Można jednak przenieść ograniczenie do błędu w czasie (przydatne podczas cyklu rozwojowego tylko):

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

Nie zalecane praktyki ; ale opcja.

Odpowiedział 13/12/2016 o 11:32
źródło użytkownik

głosy
2

Przede wszystkim, tylko Typescript wspiera geti setskładnia gdy targetting ECMAScript 5. Aby to osiągnąć, trzeba zadzwonić z kompilatora

tsc --target ES5

Interfejsy nie obsługują pobierające i ustawiające. Aby otrzymać kod do kompilacji trzeba by zmienić go na

interface I { 
    getName():string;
}

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

Co maszynopis obsługuje to specjalna składnia polach konstruktorów. W twoim przypadku, można mieć

interface I {
    getName():string;
}

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

Zauważ, jak klasa Cnie określa pola name. To jest faktycznie uznane za pomocą cukru składniowej public name: stringw konstruktorze.

Jak Sohnee wskazuje interfejs jest rzeczywiście miało ukryć żadnych szczegółów implementacyjnych. W moim przykładzie wybrałem interfejs do żądania metodę getter java stylu. Można jednak również nieruchomości i pozwól klasa zdecydować, jak implementować interfejs.

Odpowiedział 11/10/2012 o 12:45
źródło użytkownik

głosy
0

Korzystanie maszynopis 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());

Patrz przykład na maszynopis Playground .

Odpowiedział 25/05/2019 o 17:30
źródło użytkownik

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