简体   繁体   English

TypeScript 需要类型检查

[英]TypeScript require with type checking

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.我正在使用 TypeScript v1.4.1 并希望需要一个外部模块(在本例中为“chai”)并对其进行类型检查。

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();
   });
});

With this definition file:使用此定义文件:

declare module chai {
   ...
}
declare module "chai" {
   export = chai;
}

Compiling gives these errors:编译会出现这些错误:

test/test.ts(5,5): error TS2300: Duplicate identifier 'chai'.
typings/chai/chai.d.ts(6,16): error TS2300: Duplicate identifier 'chai'.

It seems my only option is rename my chai variable name in test.ts.看来我唯一的选择是在 test.ts 中重命名我的chai变量名。 That seems clunky AND won't type check the use of the renamed chai variable.这看起来很笨重,并且不会对重命名的chai变量的使用进行类型检查。

Any advice?有什么建议吗?

Use the import keyword with require instead of varimport关键字与require一起使用,而不是var

import chai = require('chai');

And compile with --module commonjs if you're not already如果您还没有,请使用--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");

Since TypeScript 3.9 Beta was released it's possible to use require with typing由于TypeScript 3.9 Beta已发布,因此可以在键入时使用require

Example:例子:

const {someValue} = require('fs')

"TypeScript now automatically detects the types of imports you're using to keep your file's style clean and consistent." “TypeScript 现在会自动检测您使用的导入类型,以保持文件样式的简洁和一致。”

ref.参考https://devblogs.microsoft.com/typescript/announcing-typescript-3-9-beta/ https://devblogs.microsoft.com/typescript/annoucing-typescript-3-9-beta/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM