首页 文章

在编写自定义TypeScript定义文件时出现错误“模块'name'解析为...处的无类型模块”

提问于
浏览
23

我找不到我安装的NodeJS软件包的TypeScript定义 @type/{name} ,所以我尝试为它编写一个 d.ts 文件,并将该文件放在 {project root}\typings 文件夹中 . 这是我的方式:

// My source code: index.ts
import Helper from 'node-helper-lib';


// My definition: \typings\node-helper-lib.d.ts
declare....(something else)

declare module 'node-helper-lib' {
   class Helper { ... }
   export = Helper;
}

但是,Visual Studio代码不断产生此错误并将红线置于 declare module 'node-helper-lib' 下:

[ts]增强中的模块名称无效 . 模块'node-helper-lib'解析为' \ node_modules \ node-helper-lib \ index.js'中的无类型模块,该模块无法扩充 .

这是不合法的,因为库是无类型的,所以我应该被允许添加输入?

UPDATE:

我在用:

  • TypeScript:2.1.4

  • Visual Studio代码:1.9.1

  • 节点JS:6.9.4

  • Windows 10 x64

3 回答

  • 39

    实际解决方案由@Paleo在@hirikarate的回答中给出评论:

    Imports should be declared inside the module declaration.

    例:

    declare module 'node-helper-lib' {
       import * as SomeThirdParty from 'node-helper-lib';
       interface Helper {
           new(opt: SomeThirdParty.Options): SomeThirdParty.Type
       }
       export = Helper;
    }
    
  • 0

    经过一些尝试和错误后,我发现 augmentation 表示"declaring a module in the same file with other module declaration(s)" .

    因此,如果我们要为 untyped 第三方JavaScript库编写定义文件,我们必须在该文件中只有一个 declare module 'lib-name' ,并且'lib-name'必须与库名称完全匹配(可以在其package.json,"name"属性中找到) .

    另一方面,如果包含第三方库 already has definition file .d.ts ,并且我们想要扩展其功能,那么我们可以将附加定义放在我们创建的另一个文件中 . 这叫做 augmenting .

    例如:

    // These module declarations are in same file, given that each of them already has their own definition file.
    declare module 'events' {
       // Extended functionality
    }
    
    declare module 'querystring' {
       // Extended functionality        
    }
    
    declare module '...' { ... }
    

    我在这里留下我的发现,以防有人有同样的问题 . 如果我错过了什么,请纠正我 .

  • 17

    我也收到了这个错误信息 . 对我来说问题是我试图在现有的类型定义文件中声明另一个模块,其中包含模块声明 . 将新模块声明移动到新文件后,错误消失了 .

相关问题