2017-09-13 78 views
1

所以我有一个名为Report的基类,然后我有另一个类从报告称为数据表扩展。无法在基类打字稿上调用扩展方法

我写了Report类的扩展,我希望能够在我有一个数据表对象时调用它。

简单的例子:

类在一个文件中写道

export class Report { 
    id: number; 
    name: string; 
} 

另一类在另一个文件

export class Datasheet extends Report { 
    description: string; 
} 

在这里,我已经写了报告类的简单扩展写道,在不同的文件

import { Report } from './report'; 

export {}; 

declare module './report' { 
    interface Report { 
     hasName(): boolean; 
    } 
} 

Report.prototype.hasName = function() { 
    return this.name == null || this.name.length > 0; 
}; 

所以现在我创建一个新的数据表,我想调用扩展方法.hasName(),这在打字稿编译罚款,但是当它被发送到浏览器中,我得到一个错误说

m.hasName不是函数

例如,我将要做到这一点(简单实例)

const m = new Datasheet(); 
const check = m.hasName(); 

为什么当编译好的时候出现错误?我正在使用Typescript 2.4.2。

我想写这个,就像你可以C#对象,并写入扩展方法。这使我的物体保持干净

任何帮助将不胜感激!

+0

有没有原因你不直接添加'hasName()'方法到Report类? – JasonK

+0

当我将所有内容放入单个文件而无需导入或声明模块时,代码问题适用于我。扩展方法的真名是什么 - “hasName”或“hasDescription”?是否在调用'new Datasheet()'之前在浏览器中执行对Report.prototype.hasName的赋值? – artem

+0

在您使用它们的文件中,您是否导入模块扩展?我试过,并在节点上它为我工作(在声明中将'hasDescription'更改为'hasName',假设它是一个错字) –

回答

0

您在Typescript中不需要prototype语法,编译器会为您创建该语法。优选地,您也不需要Object.assign,特别是当问题只能用类语法解决时。

这显示了如何有一个Datasheet延伸Report,以便您可以拨打hasName()

interface IReport { 
    hasName():boolean 
} 

class Report implements IReport { 
    id: number 
    name: string 
    hasName() { 
     return this.name == null || this.name.length > 0; 
    } 
} 

class Datasheet extends Report { 
    description: string 
} 

const m = new Datasheet(); 
const check = m.hasName(); 
+0

但我没有想直接创建对我的对象的功能 – Gillardo

+0

你不会。如果你编译我的答案,你会发现javascript和你在文章中写的一样:'Report.prototype。hasName = function(){ return this.name == null || this.name.length> 0; };' – Kokodoko

+0

,但是您已经直接针对'Report'对象声明了'hasName()'方法.... – Gillardo