如果存在“import x = require(”x“);”types x“require(”x“),则打字稿”声明合并“不起作用;”

时间:2015-09-07 14:51:57

标签: node.js typescript visual-studio-2015

Typescript中的"declaration merging"表示“编译器正在将使用相同名称声明的两个单独声明合并到一个定义中。”

然而,我遇到一种情况,我不知道为什么这两个接口声明无法合并。

(环境是“visual studio 2015社区”+“用于Visual Studio的Node.js工具”(由微软制作))

首先,有一个名为'b.ts'的文件,您可以在其中放入任何内容,只需确保b.ts确认为模块(例如,至少有一个导出声明)。另一个名为'a.ts'的文件,其内容如下:

b.ts

export var c;

a.ts

import a = require("b");

// ErrorConstructor is declared in the lib.d.ts from "Node.js Tools for Visual Studio". 
//
// interface ErrorConstructor {
//   new (message?: string): Error;
//   (message?: string): Error;
//   prototype: Error;
// }
//
// However, it lacks the prepareStackTrace property, so I added it, and 
// expect typescript could 'merge' this one with the original one.

interface ErrorConstructor {
    prepareStackTrace: any;
}

function test() {
    var a = Error.prepareStackTrace; // The typescript complains that
                                     // Property 'prepareStackTrace' does not 
                                     // exist on type 'ErrorConstructor'.
}

正如您在评论中看到的那样,typescript编译器抱怨'Error.prepareStackTrace'不存在。

但是,如果我注释掉“import a = require(”b“)”行,则错误消失了!

//import a = require("b");

interface ErrorConstructor {
    prepareStackTrace: any;
}

function test() {
    var a = Error.prepareStackTrace;  // <-- no error!
}

如果有“import x = require(”x“);”,我不知道为什么打字稿无法执行声明合并。有人可以帮我吗?感谢。

2 个答案:

答案 0 :(得分:4)

来自http://basarat.gitbooks.io/typescript/content/docs/project/modules.html

  

如果您在TypeScript文件的根级别进行导入或导出,则会在该文件中创建本地范围

答案 1 :(得分:1)

我想我找到了答案:https://github.com/Microsoft/TypeScript/issues/2821#issuecomment-94093212

&#34;通过将导入或导出添加到文件中的顶级作用域,您可以将此文件整合到一个模块中。&#34;

我认为如果至少有一个&#39; export&#39;,那么该文件将成为一个模块(因为Typescript编译器会生成一个包装文件内容的函数)。但是,通过该评论,如果至少有一个&#39; import&#39;,该文件也将成为一个模块。