是否可以在接口定义中使用getter/setter?

Iva*_*pov 76 get interface accessor set typescript

目前,TypeScript不允许在接口中使用get/set方法(访问器).例如:

interface I {
      get name():string;
}

class C implements I {
      get name():string {
          return null;
      } 
}
Run Code Online (Sandbox Code Playgroud)

此外,TypeScript不允许在类方法中使用Array Function Expression:例如:

class C {
    private _name:string;

    get name():string => this._name;
}
Run Code Online (Sandbox Code Playgroud)

有没有其他方法可以在接口定义上使用getter和setter?

Fen*_*ton 105

您可以在界面上指定属性,但不能强制使用是否使用了getter和setter,如下所示:

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);
Run Code Online (Sandbox Code Playgroud)

在这个例子中,接口不强制类使用getter和setter,我可以使用一个属性代替(下面的例子) - 但是接口应该隐藏这些实现细节,因为它是对调用代码的承诺关于它可以称之为什么.

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);
Run Code Online (Sandbox Code Playgroud)

最后,=>不允许使用类方法 - 如果你认为有一个烧录用例,你可以开始讨论Codeplex.这是一个例子:

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

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

    // No
    get name() => 'Steve';
}
Run Code Online (Sandbox Code Playgroud)


Mei*_*hes 32

要补充其他答案,如果您希望get value在界面上定义,则可以执行以下操作:

interface Foo {
  readonly value: number;
}

let foo: Foo = { value: 10 };

foo.value = 20; //error

class Bar implements Foo {
  get value() {
    return 10;
  }
}
Run Code Online (Sandbox Code Playgroud)

但据我所知,正如其他人所提到的,目前无法在界面中定义只设置属性.但是,您可以将限制移动到运行时错误(仅在开发周期中有用):

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");
  }
}
Run Code Online (Sandbox Code Playgroud)

不建议练习 ; 但是一个选择.