TypeScript要求进行类型检查 [英] TypeScript require with type checking

查看:200
本文介绍了TypeScript要求进行类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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.

有什么建议吗?

推荐答案

使用 关键字,用require代替var

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要求进行类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆