2017-06-05 112 views
0

我有一个具有大量类的CPU约束项目,我使用接口来最小化每个模块中使用的导入数量。但是,在声明实现各自接口的类的私有方法时,我遇到了一些问题。目前,我遇到:在TypeScript类中实现接口的私有方法

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) 
    } 
} 

的问题是,打字稿似乎不会让我在这个类中声明私有属性。由于是,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'. 

我在做什么错在这里?你可以简单地不声明私有成员实现接口的类吗?

作为参考,Colony.tshereindex.d.ts相关部分是here

+0

似乎在[游乐场]做工精细(https://www.typescriptlang.org/play/)。哪个版本的TypeScript/tsc? – jonrsharpe

+1

现在,您的问题的代码正在运行。我期望在界面中取消注释时发生错误。您可能想要显示产生错误的每一位代码以及错误。 –

+0

我已将Github链接添加到完整的代码中。 @jonrsharpe,我正在运行TypeScript 2.3.3。 –

回答

1

你可能做类似的东西:

function fn(): IColony { ... } 

let a: Colony = fn(); // error: Type 'IColony' is not assignable to type 'Colony'... 

,因为你正在努力的IColony一个实例分配给Colony类型的变量,它不工作的方式(只有等出现此错误周围)。

如果是这样的话,那么它应该是:

let a: IColony = fn(); 
相关问题