TypeScript:扩展模块时如何编写定义?

问题描述 投票:0回答:3

我在 TypeScript 测试中使用助手扩展了 Chai。

import * as chai from 'chai';

chai.use((_chai) => {
  let Assertion = _chai.Assertion;
  Assertion.addMethod('sortedBy', function(property) {
    // ...
  });
});

const expect = chai.expect;

在同一个文件中测试用例使用此方法:

expect(tasks).to.have.been.sortedBy('from');

编译器给出错误“类型‘断言’上不存在属性‘sortedBy’”。

如何将

sortedBy
的声明添加到
Chai.Assertion

我尝试添加模块声明,就像其他 Chai 插件模块一样,但它不起作用。

declare module Chai {
  interface Assertion {
    sortedBy(property: string): void;
  }
}

我不想让助手成为一个单独的模块,因为它很琐碎。

typescript chai
3个回答
4
投票

尝试以下操作:

在 chaiExt.ts 中扩展 chai,如下所示:

declare module Chai 
{
    export interface Assertion 
    {
        sortedBy(property: string): void;
    }
}

在 chaiConsumer.ts 中消费:

import * as chai from 'chai';
//...
chai.expect(tasks).to.have.been.sortedBy('from');

[编辑]

如果您使用“导入” - 将文件转换为外部模块,并且不支持声明合并:link


0
投票

您的代码是正确的。模块和接口默认在 TS 上打开,因此您可以重新声明和扩充它们。

一般来说,在这种情况下我会做的是:我在与我的项目相同的文件夹中创建一个 globals.d.ts 文件,这样 .d.ts 将自动加载,然后我会根据您的需要添加类型定义做到了。

declare module Chai {
  interface Assertion {
    sortedBy(property: string): void;
  }
} 

0
投票

当我想扩展 chai 断言时,我需要稍微不同地声明接口

declare global {
  namespace Chai {
    interface Assertion {
      sortedBy(property: string): void;
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.