问题描述
我正在使用TypeScript v1.4.1,并且需要一个外部模块(在这种情况下为"chai")并进行类型检查.
I am using TypeScript v1.4.1 and would like to require an external module (in this case "chai") and have it be type checked.
但是,我与此代码发生某种命名冲突:
However, I am running into some sort of naming conflict with this code:
/// <reference path="../typings/node/node.d.ts" />
/// <reference path="../typings/chai/chai.d.ts" />
/// <reference path="../typings/mocha/mocha.d.ts" />
var chai = require("chai");
var expect = chai.expect;
var assert = chai.assert;
describe("TEST", () =>
{
it("true should be true", (done)=>
{
expect(true).to.be.true;
done();
});
});
使用此定义文件:
declare module chai {
...
}
declare module "chai" {
export = chai;
}
编译会出现以下错误:
test/test.ts(5,5): error TS2300: Duplicate identifier 'chai'.
typings/chai/chai.d.ts(6,16): error TS2300: Duplicate identifier 'chai'.
似乎我唯一的选择是在test.ts中重命名我的chai
变量名.这似乎很笨拙,并且不会键入检查重命名的chai
变量的使用情况.
It seems my only option is rename my chai
variable name in test.ts. That seems clunky AND won't type check the use of the renamed chai
variable.
有什么建议吗?
推荐答案
import chai = require('chai');
如果尚未使用--module commonjs
进行编译
或者,如果由于某种原因您不希望测试代码成为外部模块,则添加类型注释将保留类型检查.
Or, if for some reason you don't want the test code to be an external module, adding a type annotation will preserve type checking.
var c: typeof chai = require("chai");
这篇关于TypeScript要求进行类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!