如何将类型与模块一起导出?

How to export typings along with a module?

我正在编写一个模块,为我们团队正在使用的测试套件添加一些功能。这是一个包含主要打字稿文件的项目,它包装了我们项目的其他出口。

index.d.ts:

export * from "./OneModule"
export * from "./AnotherModule"

其中一个模块具有向 Chai.js 断言库添加新方法的功能。这是通过使用它的功能来添加新方法来实现的,例如:

assertion.addChainableMethod('newMethod', callback, chainCallback)

将增加编写 expect(something).to.be.newMethod() 等语句的能力。但是,TypeScript 无法识别这些新方法,因为 @types/chai 中的类型断言显然没有这些功能。

我创建了要与 Chai 断言合并的接口定义,如下所示:

declare namespace Chai {
    interface Assertion {
        newMethod(something: string): Assertion;
        newMethod: Assertion;
    }
}

addChainableMethod 添加了新方法,因此它也可以作为 expect(something).to.be.newMethod.equals() 链,这就是为什么它必须同时定义为 属性 和方法。

问题是,无论我如何将上述声明添加到 index.d.ts,新断言在导入项目中都不可见。我怀疑它以某种方式包含在模块名称空间中(但我对此可能是非常错误的)。我知道我可以 @types/newAssertions 并在那里定义它们,但这需要用户在 package.json 中包含 2 个项目,并且还需要我们的开发人员同时处理 2 个项目。如何导出我的 Chai 命名空间扩展和我拥有的所有模块?

我做过的最好的事情是这样的:

declare module 'my-module' {
    function AddNewAssertions(chai: any, utils: any): void;
}
declare namespace Chai {
    interface Assertion { //same as above }
}

但是这样我就无法公开我的其他模块,并且它仅在我仅公开添加这些断言的 AddNewAssertions 函数时才有效。不过这很完美。

我为此编写了一个非常基本的测试应用程序,并成功添加了:

declare global {
    namespace Chai {
        interface Assertion {
            newMethod(something: string): Assertion;
            newMethod: Assertion;
        }
    }
}

这使得扩展在您的其他模块中可见,而不仅仅是带有声明的模块。