目前,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?
发布于 2012-10-11 20:03:53
您可以在接口上指定属性,但不能强制是否使用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);
最后,类方法不允许使用=>
-如果您认为它有一个刻录用例,您可以使用start a discussion on Codeplex。下面是一个示例:
class Test {
// Yes
getName = () => 'Steve';
// No
getName() => 'Steve';
// No
get name() => 'Steve';
}
发布于 2016-12-13 19:32:38
为了补充其他答案,如果您希望在接口上定义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;
}
}
但据我所知,正如其他人所提到的,目前还没有办法在接口中定义一个仅限set的属性。但是,您可以将限制转移到运行时错误(仅在开发周期中有用):
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;而是一个选项。
发布于 2012-10-11 19:45:54
首先,当面向Ecmascript 5时,Typescript只支持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方法的接口。但是,您也可以创建一个属性,然后让类决定如何实现该接口。
https://stackoverflow.com/questions/12838248
复制相似问题