我在界面上有以下字段:
// Stores the to views folder
VIEW_PATH: string;
// Stores BrowserWindows with respective view
browserWindows: [string, BrowserWindow | null][];
当我将班级中的字段设为无效,并尝试将它们设置为私有时,出现此错误:
Class 'WindowHandler' incorrectly implements interface 'IWindowHandler'.
Property 'VIEW_PATH' is private in type 'WindowHandler' but not in type 'IWindowHandler'.ts(2420)
当我尝试将界面字段设置为私有时:
'private' modifier cannot appear on a type member.ts(1070)
答案 0 :(得分:1)
接口本质上是公共的,因此只能具有公共成员,因此它们不接受私有/受保护等定义。另一方面,接口的实现(例如类)可以具有私有成员/方法来获取其实现细节。
您可能已经误解了接口的概念,它是您与公共世界之间的一种“合同”,因此在这些合同中没有逻辑地使用“隐藏”元素,或者您正试图使用它们以不正确的方式。让我知道您的用例是什么,为什么要让某些成员私有以进一步帮助您。
答案 1 :(得分:0)
作为补充答案:
TypeScript 接口确实只描述了一个公共契约。在 TS 术语中,它们描述了 shape of values。请求者(他们也不是唯一寻求此方法的人 - 例如,参见 this GitHub issue)将接口成员设为私有是因为具有相同 private
成员的两个不相关的类被认为不兼容,尽管结构相同。
与 handbook example 类似,以下会导致类型错误:
class A { private a : string = ""; }
class B { private a : string = ""; }
let a = new A();
a = new B(); //Types have separate declarations of a private property 'a'.
这样做,意味着私有成员做有助于类的形状:
class C implements B { //Types have separate declarations of a private property 'a'.
private a : string = "";
}
然而,这些类不会“从同一个声明中共享其形状的私有方面”(同上)。只有子类可以与其超类共享形状的私有部分:
class D extends B { //OK
constructor() {
super();
}
}
因此,只有类有 private
成员。作为允许接口实现 protected
成员(本质上非常相似)was declined as unsafe 的提议,这也不太可能改变。
另见:
private
成员 affect compatibility。