我有一个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'.
我在这做错了什么?你能不能在实现接口的类上声明私有成员?
你可能正在做类似的事情:
function fn(): IColony { ... }
let a: Colony = fn(); // error: Type 'IColony' is not assignable to type 'Colony'...
发生此错误的原因是您尝试将IColony
的实例分配给Colony
类型的变量,并且它不能以这种方式工作(只有相反的方式)。
如果是这样的话那应该是:
let a: IColony = fn();
这是因为
接口定义了“公共”合同,因此在接口上使用
protected
或private
访问修饰符是没有意义的,更多的是让我们称之为实现细节。因此,您无法通过界面执行所需操作。