在 Typescript 中实现接口时如何定义私有属性?

编程入门 行业动态 更新时间:2024-10-25 02:29:42
本文介绍了在 Typescript 中实现接口时如何定义私有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在我的项目中使用 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 中实现接口时如何定义私有属性?

本文发布于:2023-06-12 05:14:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/651977.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   接口   定义   Typescript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!