在 Typescript 中实现接口时如何定义私有属性? [英] How to define a private property when implementing an interface in Typescript?

查看:82
本文介绍了在 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?

推荐答案

接口定义公共"合同,因此在接口上使用 protectedprivate 访问修饰符是没有意义的,它们更像是一个,让我们称之为实现细节.出于这个原因,你不能用界面做你想做的事.

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 访问修饰符 - https://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 - https://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 中实现接口时如何定义私有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆