我想定义一个具有readonly属性的接口.例如;
interface foo {
get bar():bool;
}
Run Code Online (Sandbox Code Playgroud)
但是,这会在语法上出现语法错误"expected';'".我已将VisualStudio设置为使用ES5目标,因此支持getter.这是接口的限制吗?未来可能会发生这种变化; 这是一件非常好的事情.
Vit*_*kov 70
在Typescript 2.0中引入了仅限 Getter的属性:
interface foo {
readonly bar: boolean;
}
Run Code Online (Sandbox Code Playgroud)
Val*_*tin 22
是的,这是接口的限制.是否使用getter实现对属性的访问是一个实现细节,因此不应该是公共接口的一部分.另见这个问题.
如果需要在接口中指定readonly属性,可以添加getter方法:
interface foo {
getAttribute() : string;
}
Run Code Online (Sandbox Code Playgroud)
正如@Vitaliy Ulantikov 回答的那样,您可以使用readonly正如@Vitaliy Ulantikov 回答的那样,您可以在属性上这与吸气剂完全一样。
interface Point {\n readonly x: number;\n readonly y: number;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n当对象文字实现接口时,您不能覆盖readonly属性:
let p1: Point = { x: 10, y: 20 };\np1.x = 5; // error!\nRun Code Online (Sandbox Code Playgroud)\n\n但上课的时候实现了该接口时,就无法避免覆盖它。
\n\nclass PointClassBroken implements Point {\n // these are required in order to implement correctly\n x: number;\n y: number;\n\n constructor(x: number, y: number) {\n this.x = x\n this.y = y\n }\n\n changeCoordinates(x: number, y: number): void {\n this.x = x // no error!\n this.y = y // no error!\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我猜想\xe2\x80\x99s是因为当你在类定义中重新声明属性时,它们会覆盖接口的属性,并且不再是只读的。
\n\n要解决这个问题,请使用readonly直接在实现该接口的类中使用属性
class PointClassFixed implements Point {\n readonly x: number;\n readonly y: number;\n\n constructor(x: number, y: number) {\n this.x = x\n this.y = y\n }\n\n changeCoordinates(x: number, y: number): void {\n this.x = x // error!\n this.y = y // error!\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n到操场上亲自看看吧。
\n| 归档时间: |
|
| 查看次数: |
26372 次 |
| 最近记录: |