我在我的项目中使用 TypeScript,但遇到了一个问题.我正在定义这样的接口:
I'm using TypeScript in my project and I have come across an issue. I'm defining an interface like this:
interface IModuleMenuItem { name: string; }我想创建一个从这个接口实现的类,但我希望名称是这样的私有属性:
I want to create a class that implements from this interface but I want the name to be a private property like this:
class ModuleMenuItem implements IModuleMenuItem { private name: string; }我收到以下错误:
类 ModuleMenuItem 错误地实现了接口 IModuleMenuItem.属性名称在 ModuleMenuItem 类型中是私有的,但在类型中不是IModuleMenuItem.
Class ModuleMenuItem incorrectly implements interface IModuleMenuItem. Property name is private in type ModuleMenuItem but not in type IModuleMenuItem.
在实现接口时如何将属性定义为私有或受保护的?
How can I define a property as private or protected when implementing an interface?
推荐答案接口定义公共"合同,因此在接口上使用 protected 或 private 访问修饰符是没有意义的,它们更像是一个,让我们称之为实现细节.出于这个原因,你不能用界面做你想做的事.
Interfaces define "public" contracts and as such it doesn't make sense to have protected or private access modifier on interfaces, which are more of a, let's call it, implementation detail. For that reason you can't do what you want with an interface.
如果您想让属性对消费者只读,但在子类中可覆盖,那么您可以执行以下操作:
If you want to make the property read-only to consumers, but overridable in a subclass then you can do something like this:
interface IModuleMenuItem { getName(): string; } class ModuleMenuItem implements IModuleMenuItem { private name; public getName() { return name; } protected setName(newName : string) { name = newName; } }我认为在 TypeScript 2.0(尚未发布)中,如果您在初始化时只读字段之后使用 readonly 访问修饰符 - basarat.gitbooks.io/typescript/content/docs/types/readonly.html>
I think in TypeScript 2.0 (not out yet) you will be able to use the readonly access modifier if you were after initialization-time readonly field - basarat.gitbooks.io/typescript/content/docs/types/readonly.html
interface IModuleMenuItem { readonly name : string; } class ModuleMenuItem implements IModuleMenuItem { public readonly name : string; constructor() { name = "name"; } }更多推荐
在 Typescript 中实现接口时如何定义私有属性?
发布评论