2015-09-07 133 views
1

Typescript中的"declaration merging"表示“编译器正在完成将两个用相同名称声明的单独声明合并成一个单一定义的工作。”如果有“import x = require(”x“);”“声明合并”不起作用“

但是,我遇到一种情况,我不知道为什么这两个接口声明不能合并。

(的环境是 “视觉工作室2015年社区” + “Node.js加载工具为Visual Studio”(由微软,太))

首先,有一个名为 'b.ts',你的文件可以放入任何东西,只要确保b.ts ack作为一个模块(例如,至少有一个导出声明)。并命名为 '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'. 
} 

正如你可以在注释中看到,打字稿编译器抱怨'Error.prepareStackTrace'不存在。

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

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

interface ErrorConstructor { 
    prepareStackTrace: any; 
} 

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

我不知道为什么打字稿不能执行该声明合并如果有“导入X =要求(” X“);”。任何人都可以帮助我吗?谢谢。

回答

1

我想我找到了答案:“通过增加进口或出口到顶级的范围在您的文件,你修整这个文件放到一个模块” https://github.com/Microsoft/TypeScript/issues/2821#issuecomment-94093212

我想如果至少有一个'导出',那么该文件将成为一个模块(因为Typescript编译器会生成一个函数来包装文件内容)。但是,通过该评论,如果至少有一个“导入”,该文件也将成为一个模块。