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

时间:2022-09-24 22:47:05

At the moment, TypeScript does not allow use get/set methods(accessors) in interfaces. For example:

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

interface I {
      get name():string;
}

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

furthermore, TypeScript does not allow use Array Function Expression in class methods: for ex.:

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

class C {
    private _name:string;

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

Is there any other way I can use a getter and setter on an interface definition?

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

3 个解决方案

#1


74  

You can specify the property on the interface, but you can't enforce whether getters and setters are used, like this:

您可以在界面上指定属性,但不能强制使用是否使用了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);

In this example, the interface doesn't force the class to use getters and setters, I could have used a property instead (example below) - but the interface is supposed to hide these implementation details anyway as it is a promise to the calling code about what it can call.

在这个例子中,接口不强制类使用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);

And lastly, => is not allowed for class methods - you could start a discussion on Codeplex if you think there is a burning use case for it. Here is an example:

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

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

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

    // No
    get name() => 'Steve';
}

#2


18  

To supplement the other answers, if your desire is to define a get value on an interface, you can do this:

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

interface Foo {
  readonly value: number;
}

let foo: Foo = { value: 10 };

foo.value = 20; //error

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

but as far as I'm aware, and as others mentioned, there is no way currently to define a set-only property in the interface. You can, however, move the limitation to a run-time error (useful during the development cycle only):

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

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

Not recommended practice; but an option.

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

#3


2  

First of all, Typescript only supports get and set syntax when targetting Ecmascript 5. To achieve this, you have to call the compiler with

首先,Typescript只在目标Ecmascript 5时支持get和set语法。为此,你必须调用编译器

tsc --target ES5

Interfaces do not support getters and setters. To get your code to compile you would have to change it to

接口不支持getter和setter。要使代码编译,您必须将其更改为

interface I { 
    getName():string;
}

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

What typescript does support is a special syntax for fields in constructors. In your case, you could have

什么打字稿支持的是构造函数中字段的特殊语法。在你的情况下,你可以

interface I {
    getName():string;
}

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

Notice how class C does not specify the field name. It is actually declared using syntactic sugar public name: string in the constructor.

注意C类没有指定字段名称。它实际上是在构造函数中使用语法糖公共名称:string声明的。

As Sohnee points out, the interface is actually supposed to hide any implementation details. In my example, I have chosen the interface to require a java-style getter method. However, you can also a property and then let the class decide how to implement the interface.

正如Sohnee指出的那样,界面实际上应该隐藏任何实现细节。在我的例子中,我选择了接口来要求一个java风格的getter方法。但是,您也可以使用属性然后让类决定如何实现该接口。

#1


74  

You can specify the property on the interface, but you can't enforce whether getters and setters are used, like this:

您可以在界面上指定属性,但不能强制使用是否使用了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);

In this example, the interface doesn't force the class to use getters and setters, I could have used a property instead (example below) - but the interface is supposed to hide these implementation details anyway as it is a promise to the calling code about what it can call.

在这个例子中,接口不强制类使用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);

And lastly, => is not allowed for class methods - you could start a discussion on Codeplex if you think there is a burning use case for it. Here is an example:

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

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

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

    // No
    get name() => 'Steve';
}

#2


18  

To supplement the other answers, if your desire is to define a get value on an interface, you can do this:

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

interface Foo {
  readonly value: number;
}

let foo: Foo = { value: 10 };

foo.value = 20; //error

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

but as far as I'm aware, and as others mentioned, there is no way currently to define a set-only property in the interface. You can, however, move the limitation to a run-time error (useful during the development cycle only):

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

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

Not recommended practice; but an option.

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

#3


2  

First of all, Typescript only supports get and set syntax when targetting Ecmascript 5. To achieve this, you have to call the compiler with

首先,Typescript只在目标Ecmascript 5时支持get和set语法。为此,你必须调用编译器

tsc --target ES5

Interfaces do not support getters and setters. To get your code to compile you would have to change it to

接口不支持getter和setter。要使代码编译,您必须将其更改为

interface I { 
    getName():string;
}

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

What typescript does support is a special syntax for fields in constructors. In your case, you could have

什么打字稿支持的是构造函数中字段的特殊语法。在你的情况下,你可以

interface I {
    getName():string;
}

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

Notice how class C does not specify the field name. It is actually declared using syntactic sugar public name: string in the constructor.

注意C类没有指定字段名称。它实际上是在构造函数中使用语法糖公共名称:string声明的。

As Sohnee points out, the interface is actually supposed to hide any implementation details. In my example, I have chosen the interface to require a java-style getter method. However, you can also a property and then let the class decide how to implement the interface.

正如Sohnee指出的那样,界面实际上应该隐藏任何实现细节。在我的例子中,我选择了接口来要求一个java风格的getter方法。但是,您也可以使用属性然后让类决定如何实现该接口。