TypeScript:扩展模块时如何编写定义?
TypeScript: How to write definition when I extend a module?
我在 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');
编译器给出错误 "Property 'sortedBy' does not exist on type 'Assertion'"。
如何将 sortedBy
的声明添加到 Chai.Assertion
?
我试过添加模块声明,就像其他 Chai 插件模块一样,但它不起作用。
declare module Chai {
interface Assertion {
sortedBy(property: string): void;
}
}
我不想让助手成为一个单独的模块,因为它很琐碎。
尝试以下操作:
像这样在 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');
[编辑]
如果您正在使用 'import' - 您将文件转换为外部模块并且不支持声明合并:link
您的代码是正确的。模块和接口在 TS 上默认打开,因此您可以重新声明和扩充它们。
一般来说,我在这种情况下所做的是:我在与我的项目相同的文件夹中创建一个 globals.d.ts 文件,这样 .d.ts 将被自动加载,然后我会像您一样添加类型定义。
declare module Chai {
interface Assertion {
sortedBy(property: string): void;
}
}
我在 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');
编译器给出错误 "Property 'sortedBy' does not exist on type 'Assertion'"。
如何将 sortedBy
的声明添加到 Chai.Assertion
?
我试过添加模块声明,就像其他 Chai 插件模块一样,但它不起作用。
declare module Chai {
interface Assertion {
sortedBy(property: string): void;
}
}
我不想让助手成为一个单独的模块,因为它很琐碎。
尝试以下操作:
像这样在 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');
[编辑]
如果您正在使用 'import' - 您将文件转换为外部模块并且不支持声明合并:link
您的代码是正确的。模块和接口在 TS 上默认打开,因此您可以重新声明和扩充它们。
一般来说,我在这种情况下所做的是:我在与我的项目相同的文件夹中创建一个 globals.d.ts 文件,这样 .d.ts 将被自动加载,然后我会像您一样添加类型定义。
declare module Chai {
interface Assertion {
sortedBy(property: string): void;
}
}