【问题标题】:Typescript "declaration merging" does not work if there is an "import x = require("x");"如果存在“import x = require("x");”,则打字稿“声明合并”不起作用
【发布时间】:2015-12-03 04:06:39
【问题描述】:

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

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

(环境是“visual studio 2015 community”+“Node.js Tools for Visual Studio”(也是微软制作的))

首先,有一个名为“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'.
}

正如您在 cmets 中看到的,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");”,我不知道为什么 typescript 无法执行声明合并。有人可以帮我吗?谢谢。

【问题讨论】:

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


    【解决方案1】:

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

    如果您在 TypeScript 文件的根级别有导入或导出,那么它会在该文件中创建一个本地范围

    【讨论】:

    • 谢谢!这真的很有帮助。
    【解决方案2】:

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

    “通过将导入或导出添加到文件的顶级范围,您可以将此文件转换为模块。”

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 2018-03-22
      • 2019-03-03
      • 2021-05-28
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      相关资源
      最近更新 更多