【发布时间】:2017-09-13 13:33:15
【问题描述】:
所以我有一个名为 Report 的基类,然后我有另一个从 Report 扩展的名为 Datasheet 的类。
我已经为 Report 类编写了一个扩展,我希望能够在我有一个 Datasheet 对象时调用它。
简单示例:
类写在一个文件中
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# 对象一样,并编写扩展方法。这让我的物品保持整洁
任何帮助将不胜感激!
【问题讨论】:
-
有没有理由不直接将
hasName()方法添加到Report 类中? -
当我将所有内容放在一个文件中而不导入或声明模块时,有问题的代码对我有用。扩展方法的真名是什么 -
hasName或hasDescription?对Report.prototype.hasName的赋值是否在调用new Datasheet()之前在浏览器中执行? -
在您使用它们的文件中,您是否导入了模块扩展名?我试过了,在节点上它对我有用(在声明中将
hasDescription更改为hasName,假设这是一个错字) -
是什么导致扩展模块被加载?
-
不知道为什么,但我首先在对象上执行此操作
const report = Object.assign(new Report(), this.report);return report.hasName();
标签: javascript html typescript web typescript2.0