简体   繁体   English

导入Node模块时TypeScript编译器错误?

[英]TypeScript compiler error on importation of Node module?

I'm trying to use this but the compiler is producing the following: 我正在尝试使用此功能,但是编译器生成以下内容:

Client.ts(2,5): error TS2134: Subsequent variable declarations must have the same type. 
Variable 'XMLHttpRequest' must be of type '{ prototype: XMLHttpRequest; LOADING: number; 
DONE: number; UNSENT: number; OPENED: number; HEADERS_RECEIVED: number; new(): 
XMLHttpRequest; }', but here has type 'any'.

For reference the line producing the error is: 作为参考,产生错误的行是:

var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

Am I right in assuming that this is because node.d.ts doesn't have a definition for this module? 我是否可以假设这是正确的,因为node.d.ts没有此模块的定义? If so how would I go about implementing the definition, the bit that has me confused is the prototype and new() having type XMLHttpRequest . 如果是这样,我将如何实现定义,让我感到困惑的是prototype和具有XMLHttpRequest类型的new() Is this a recursive reference or will say an empty class declaration suffice? 这是递归引用还是说一个空的类声明就足够了?

This is because XMLHttpRequest is defined in lib.d.ts : 这是因为XMLHttpRequest是在lib.d.ts中定义的:

declare var XMLHttpRequest: {
    prototype: XMLHttpRequest;
    new (): XMLHttpRequest;
    LOADING: number;
    DONE: number;
    UNSENT: number;
    OPENED: number;
    HEADERS_RECEIVED: number;
}

This conflicts with your definition of XMLHttpRequest which is actually resolved to any 这与您对XMLHttpRequest的定义有冲突,该定义实际上已解析为any

var XMLHttpRequest

If this lib is compatible with the browser XMLHttpRequest you can do (splitting declaration and assignment). 如果该库与浏览器XMLHttpRequest兼容,则可以执行(拆分声明和分配)。 This way the compiler doesn't try to redefine it as any : 这样,编译器就不会尝试将其重新定义为any

 var XMLHttpRequest;
 XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

If not I suggest you use a different name, OR compile with --noLib compiler flag. 如果不是,我建议您使用其他名称,或者使用--noLib编译器标志进行编译。

Yes node.d.ts wouldn't have that declaration. 是的,node.d.ts将没有该声明。

I have 2 possible options for you create a node-XMLHttpRequest.d.ts manually. 我有2个可能的选项供您手动创建node-XMLHttpRequest.d.ts (I couldn't find one defined already) or use var XMLHttpRequest = <any>(require('xmlhttprequest').XMLHttpRequest); (我找不到已经定义的一个)或使用var XMLHttpRequest = <any>(require('xmlhttprequest').XMLHttpRequest);

If you are using this library a lot in your code I would recommend defining the node-XMLHttpRequest.d.ts file to get the benefit from typescript type checking. 如果您在代码中大量使用此库,我建议您定义node-XMLHttpRequest.d.ts文件,以从打字稿类型检查中受益。

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

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