目前,TypeScript
不允许在接口(interface)中使用 get/set 方法(访问器)。
例如:
interface I {
get name():string;
}
class C implements I {
get name():string {
return null;
}
}
此外,TypeScript 不允许在类方法中使用数组函数表达式: 例如:
class C {
private _name:string;
get name():string => this._name;
}
有没有其他方法可以在接口(interface)定义上使用 getter 和 setter?
最佳答案
你可以在接口(interface)上指定属性,但是你不能强制是否使用getters和setters,像这样:
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);
在这个例子中,接口(interface)不强制类使用 getter 和 setter,我本可以使用一个属性来代替(下面的例子)——但是接口(interface)应该隐藏这些实现细节,因为它 promise 关于它可以调用什么的调用代码。
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如果您认为它有一个燃烧的用例。这是一个例子:
class Test {
// Yes
getName = () => 'Steve';
// No
getName() => 'Steve';
// No
get name() => 'Steve';
}
关于interface - 是否可以在接口(interface)定义中使用 getter/setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12838248/