hubot
类型定义有以下类:
declare namespace Hubot {
// ...
class Message {
user: User;
text: string;
id: string;
}
// ...
}
// Compatibility with CommonJS syntax exported by Hubot's CoffeeScript.
// tslint:disable-next-line export-just-namespace
export = Hubot;
export as namespace Hubot;
我想从我的代码中扩充 Message
类,在我编写的 hubot.d.ts
文件中:
import * as hubot from 'hubot';
declare namespace Hubot {
export class Message {
mentions: string[]
}
}
hubot.d.ts
文件包含在代码中
"files": ["types/custom/hubot.d.ts"]
在 tsconfig.json
文件中。
我错过了什么?有什么办法吗?
最佳答案
hubot.d.ts
应该包含:
// This import serves no purpose except to make the file a module
// (so that the following statement is a module augmentation rather
// than a module declaration) and could be replaced with `export {}`.
import * as hubot from 'hubot';
declare module "hubot" {
interface Message {
mentions: string[]
}
}
A module augmentation需要将声明添加到 hubot
模块。由于 Hubot
命名空间被分配为模块的导出,因此对模块所做的任何扩充都将直接针对该命名空间;在扩充中编写另一个 namespace Hubot { ... }
会创建一个嵌套的命名空间,这不是您想要的。最后,声明一个类会出现“重复标识符”错误,而声明一个接口(interface)足以添加属性。
关于javascript - 如何扩充在 Typescript 模块上声明但未导出的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53345357/