首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否可以在接口定义中使用getters/setters?

是否可以在接口定义中使用getters/setters?
EN

Stack Overflow用户
提问于 2012-10-11 19:15:08
回答 4查看 87.8K关注 0票数 117

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

代码语言:javascript
运行
复制
interface I {
      get name():string;
}

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

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

代码语言:javascript
运行
复制
class C {
    private _name:string;

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

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-10-11 20:03:53

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

代码语言:javascript
运行
复制
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,我可以使用一个属性来代替(下面的例子)-但是接口应该隐藏这些实现细节,因为它是对调用代码的承诺,它可以调用什么。

代码语言:javascript
运行
复制
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);

最后,类方法不允许使用=> -如果您认为它有一个刻录用例,您可以使用start a discussion on Codeplex。下面是一个示例:

代码语言:javascript
运行
复制
class Test {
    // Yes
    getName = () => 'Steve';

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

    // No
    get name() => 'Steve';
}
票数 144
EN

Stack Overflow用户

发布于 2016-12-13 19:32:38

为了补充其他答案,如果您希望在接口上定义get value,您可以使用readonly

代码语言:javascript
运行
复制
interface Foo {
  readonly value: number;
}

let foo: Foo = { value: 10 };

foo.value = 20; //error

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

但据我所知,正如其他人所提到的,目前还没有办法在接口中定义一个仅限set的属性。但是,您可以将限制转移到运行时错误(仅在开发周期中有用):

代码语言:javascript
运行
复制
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");
  }
}

不是推荐的practice;而是一个选项。

票数 60
EN

Stack Overflow用户

发布于 2012-10-11 19:45:54

首先,当面向Ecmascript 5时,Typescript只支持getset语法。

代码语言:javascript
运行
复制
tsc --target ES5

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

代码语言:javascript
运行
复制
interface I { 
    getName():string;
}

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

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

代码语言:javascript
运行
复制
interface I {
    getName():string;
}

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

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

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12838248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档