【问题标题】:How to augment a module from another "plugin" module in Typescript如何从 Typescript 中的另一个“插件”模块扩充模块
【发布时间】:2017-01-08 17:25:17
【问题描述】:

如果我键入一个名为“foo”的模块,如下所示:

declare module "foo" {
    interface App {
        bar: boolean;
    }

    namespace foo {}

    function foo(): App;

    export = foo;
}

当导入另一个名为foo-plugin 的模块时,如何向App 接口添加新属性?

declare module "foo-plugin" {
    interface App {
        additional: string;
    }
}

我尝试了https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-plugin-d-ts.html 中描述的模式,但它不起作用,它只能看到bar 属性。

如果我将 App 界面设为顶级,则合并声明,但无需导入 foo-plugin

这就是 chai-as-promised 和 sinon-chai 发生的情况。此代码可以编译,但当然会引发异常,因为 eventually 未定义。它是某种 Typescript 限制并且必须被接受吗?

import { expect } from 'chai';

describe('Dummy', () => {
    it('passes', () => {
        expect('foo').to.eventually.equal(5);
    });
});

谢谢..

【问题讨论】:

  • 在你的扩展程序上使用相同的包名declare module "foo" {

标签: typescript


【解决方案1】:

在这里查看example with axios

基本上在您的插件上将其命名为与您要扩展的模块相同的名称

declare module "foo" { // foo-plugin
    interface App {
        additional: string;
    }
}

Declaration Merging on TypeScript docs

【讨论】:

  • 谢谢,我实际上可以使用上面的样式扩充“foo”模块,但我可以在不实际导入“foo-plugin”的情况下编译它(并且也有 Intellisense)。这可能是一些 Typescript 限制(我是 TS 新手)另外,100% 的健全性不是 TS 的设计目标。既然 chai-plugins 也这样做,我可能会承认。 :-D
  • 重要提示declare module foodeclare module "foo" 不同。让我困惑了一段时间。 (带引号时,它会尝试将模块解析为现有模块匹配;不带引号时,它假定您正在声明一个全新的模块/命名空间)
猜你喜欢
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 2016-08-28
相关资源
最近更新 更多