javascript - 如何扩充在 Typescript 模块上声明但未导出的类

标签 javascript typescript types

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;

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a6b283d1d43d8c7c82a4a4e22d0fc27c9964154c/types/hubot/index.d.ts#L18-L22

我想从我的代码中扩充 Message 类,在我编写的 hubot.d.ts 文件中:

import * as hubot from 'hubot';

declare namespace Hubot {
  export class Message {
    mentions: string[]
  }
}

但它不起作用: enter image description here

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/

相关文章:

javascript - 如何将带有 URL 的文本作为参数安全地传递给 CodeIgniter Controller ?

Java,继承,泛型 - 在模板方法实现中使用子类型的参数

javascript - 为什么给变量赋值给自己内存=内存?

javascript - 需要对搜索文本框进行服务器端验证

javascript - 我有几组 promise ,如何解析每组 "sequentially"?

TypeScript 联合函数类型

c++ - 从模板类中提取 typedef/using 定义

haskell - 为什么我注释这个类型签名的错误没有破坏东西?

javascript - IE 使用 html2canvas 返回空/空白 Canvas

javascript - 哪里可以找到@types/node的源代码