我在 Typescript 项目中使用 Chai.js。在我尝试将自定义匹配器添加到 chai 之前,它工作正常。
我是这样添加的:
chai.use(function(chai, util) {
chai.assertion.addMethod("failed", function () {
new chai.Assertion(this._obj.isFailed).to.be.true();
});
});
它工作正常,但是当我尝试转换这个表达式时:
expect(obj).to.have.failed();
我明白了
error TS2339: Property 'failed' does not exist on type 'Assertion'.
有没有更好的方法来扩展 chai 匹配器,同时避免类型检查器错误?
谢谢
最佳答案
@jiri-tobisek 的回答的更新:通过 npm 使用最新的 @types/chai
包,使用简单的导入而不是引用注释,现在添加助手我需要包装在 declare global
中进行扩充,否则它们不会被检测到。
这意味着,如果在普通 .ts
文件中声明内联类型(例如,在自定义匹配器定义旁边),我只需添加:
declare global {
export namespace Chai {
interface Assertion {
responseText(expectedText: string): Promise<void>;
}
}
}
如果我想将类型放入它们自己的类型定义文件 (my-custom-matcher.d.ts
),我使用:
declare module 'chai' {
global {
export namespace Chai {
interface Assertion {
responseText(expectedText: string): Promise<void>;
}
}
}
}
关于typescript - 在 Typescript 中添加 chai.js 匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32452577/