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

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

问题描述

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

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

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

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

class C {
    private _name:string;

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

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

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

推荐答案

可以在接口上指定属性,但是不能强制是否使用getter和setter,像这样:

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

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

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

最后,=> 不允许用于类方法 - 您可以开始讨论 Codeplex 如果您认为它有一个燃烧的用例.下面是一个例子:

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';
}

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

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