简体   繁体   中英

How to augment class declared but not exported on Typescript module

The hubot type definitions have the following class:

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

I want to augment the Message class from my code, inside a hubot.d.ts file I've written:

import * as hubot from 'hubot';

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

But it does not works: 在此处输入图片说明

The hubot.d.ts file is included in the code by having

  "files": ["types/custom/hubot.d.ts"]

In the tsconfig.json file.

What I'm missing? Any way to do that?

hubot.d.ts should contain:

// 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 is needed to add declarations to the hubot module. Since the Hubot namespace is assigned as the export of the module, any augmentations made to the module will target that namespace directly; writing another namespace Hubot { ... } in the augmentation would create a nested namespace, which isn't what you want. Finally, declaring a class gives a "duplicate identifier" error, while declaring an interface is sufficient to add properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM