【发布时间】:2017-11-06 15:40:14
【问题描述】:
我有一个 CPU 受限的项目,其中包含大量类,并且我使用接口来最小化我在每个模块中使用的导入数量。但是,在实现各自接口的类上声明私有方法时,我遇到了一些问题。目前,我遇到:
index.d.ts:
interface IColony {
// (other public properties)
// instantiateVirtualComponents(): void;
}
Colony.ts:
export class Colony implements IColony {
// (constructor and other methods)
private instantiateVirtualComponents(): void {
// (implementation)
}
}
问题是 TypeScript 似乎不允许我在这个类上声明私有属性。原样,tsc 抱怨:
Error:(398, 3) TS2322:Type 'IColony' is not assignable to type 'Colony'. Property 'instantiateVirtualComponents' is missing in type 'IColony'.
我很确定不应在接口中声明私有属性和方法,但为了安全起见,如果我取消注释 IColony 中的方法声明,tsc 然后会抱怨以下内容(在许多其他错误中由此产生):
Error:(10, 14) TS2420:Class 'Colony' incorrectly implements interface 'IColony'. Property 'instantiateVirtualComponents' is private in type 'Colony' but not in type 'IColony'.
我在这里做错了什么?你能不能简单地不在实现接口的类上声明私有成员?
【问题讨论】:
-
在playground 中似乎可以正常工作。哪个版本的 TypeScript/tsc?
-
现在,您问题中的代码正在运行。我预计当您在界面中取消注释该行时会发生错误。您可能希望显示产生错误的每一位代码以及错误。
-
我已将 Github 链接添加到完整代码中。 @jonrsharpe,我正在运行 TypeScript 2.3.3。
-
您根本不能使用私有成员来实现接口中定义的方法。如果您将接口视为其他对象读取以了解它们可以调用的内容的合同,这会有所帮助。如果方法是私有的,则不能被外部对象调用,因此违反了约定。
-
@MikeMcCaughan 我可能误解了你在说什么,但我知道你不能在接口中声明一个方法,然后将实现设为私有。我对相反的事情感到困惑 - 我想实现一个私有类方法,但 tsc 似乎想要在接口上声明的私有方法(然后在我这样做时抱怨)。
标签: class typescript interface private implements