目前,
TypeScript
不允许在接口中使用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;
}
还有其他方法可以在接口定义上使用 getter 和 setter 吗?
你可以在接口上指定属性,但不能强制是否使用 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);
在此示例中,接口不会强制类使用 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);
最后,
=>
不允许用于类方法 - 如果您认为有一个紧迫的用例,您可以在 Codeplex 上开始讨论。这是一个例子:
class Test {
// Yes
getName = () => 'Steve';
// No
getName() => 'Steve';
// No
get name() => 'Steve';
}
为了补充其他答案,如果您希望在接口上定义
get value
,您可以使用 readonly
:
interface Foo {
readonly value: number;
}
let foo: Foo = { value: 10 };
foo.value = 20; //error
class Bar implements Foo {
get value() {
return 10;
}
}
但据我所知,正如其他人提到的,目前无法在界面中定义仅设置的属性。但是,您可以将限制转移到运行时错误(仅在开发周期内有用):
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");
}
}
不建议这样做;但一个选择。
首先,Typescript 在针对 Ecmascript 5 时仅支持
get
和 set
语法。要实现此目的,您必须使用 调用编译器
tsc --target ES5
接口不支持 getter 和 setter。要编译您的代码,您必须将其更改为
interface I {
getName():string;
}
class C implements I {
getName():string {
return null;
}
}
TypeScript 支持的是构造函数中字段的特殊语法。对于你的情况,你可以有
interface I {
getName():string;
}
class C implements I {
constructor(public name: string) {
}
getName():string {
return name;
}
}
注意类
C
没有指定字段 name
。它实际上是在构造函数中使用语法糖public name: string
来声明的。
Sohnee 指出,接口实际上应该隐藏任何实现细节。在我的示例中,我选择了需要 java 风格的 getter 方法的接口。但是,您也可以一个属性,然后让类决定如何实现接口。
使用 TypeScript 3.4:
interface IPart {
getQuantity(): number;
}
class Part implements IPart {
private quantity: number;
constructor(quantity: number) {
this.quantity = quantity;
}
public getQuantity = (): number => {
return this.quantity;
};
}
let part = new Part(42);
// When used in typescript, quantity is not accessible.
// However, when compiled to javascript it will log '42'.
console.log(part.quantity);
// Logs '42'.
console.log(part.getQuantity());
请参阅 TypeScript Playground 上的示例。