无法在基类打字稿上调用扩展方法

时间:2017-09-13 13:33:16

标签: javascript html typescript web typescript2.0

所以我有一个名为Report的基类,然后我有另一个从Report中扩展的类,叫做数据表。

我已经为Report类编写了一个扩展,我希望能够在我有一个Datasheet对象时调用它。

简单示例:

Class在一个文件中写道

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#对象一样,并编写扩展方法。这使我的物品保持干净整洁

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分: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(); 
相关问题