在接口定义中可以使用getters / setter吗? [英] Is it possible to use getters/setters in interface definition?

查看:139
本文介绍了在接口定义中可以使用getters / setter吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  interface I {
get name():string;
}

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






$ b

此外,TypeScript不允许使用数组函数表达式类方法:
例如:

  class C {
private _name:string;

获取name():string => this._name;

$ / code>

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

解决方案

您可以在接口上指定属性,但无法强制执行是否使用getters和setters,就像这样:

  interface IExample {
名称:string;
}

类示例实现IExample {
private _name:string =Bob;

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

公共集合名称(值){
this._name = value;
}
}

var示例= new示例();
alert(example.Name);

在这个例子中,接口不强制类使用getters和setters,我可以使用了一个属性(下面的例子) - 但接口应该隐藏这些实现细节,因为它是调用代码有关它可以调用的一个承诺。

  interface IExample {
名称:string;
}

类示例实现IExample {
//这满足接口只是相同的
public Name:string =Bob;
}

var示例= new示例();
alert(example.Name);

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

  class Test {
//是
getName =()=> 史蒂夫;

//无
getName()=> 史蒂夫;

//无
获取name()=> 史蒂夫;
}


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

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.:

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?

解决方案

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

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.

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:

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

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

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

这篇关于在接口定义中可以使用getters / setter吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆