出现错误“模块‘名称’解析为无类型模块在……";编写自定义 TypeScript 定义文件时 [英] Having error "Module 'name' resolves to an untyped module at..." when writing custom TypeScript definition file

查看:95
本文介绍了出现错误“模块‘名称’解析为无类型模块在……";编写自定义 TypeScript 定义文件时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't find TypeScript definition @type/{name} for one of my installed NodeJS packages, so I attempt to write a d.ts file for it, and put the file in {project root}\typings folder. This is how I do:

// 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 Code 不断产生此错误并在 declare module 'node-helper-lib' 下放置红线:

However, Visual Studio Code keeps yielding this error and puts red line under declare module 'node-helper-lib':

[ts] 扩充中的模块名称无效.模块节点助手库"解析为{project"中的无类型模块path}\node_modules\node-helper-lib\index.js',不能为增强.

[ts] Invalid module name in augmentation. Module 'node-helper-lib' resolves to an untyped module at '{project path}\node_modules\node-helper-lib\index.js', which cannot be augmented.

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

Isn't it legit that because the library is untyped, so I should be allowed to add typing to it?

更新:

我正在使用:

  • 打字稿:2.1.4
  • Visual Studio 代码:1.9.1
  • 节点 JS:6.9.4
  • Windows 10 x64

推荐答案

经过一些尝试和错误,我发现 augmentation 的意思是在同一个文件中声明一个模块与其他模块声明(S)".

After some tries and errors, I found that augmentation means "declaring a module in the same file with other module declaration(s)".

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

Therefore if we want to write a definition file for an untyped 3rd-party JavaScript library, we must have ONLY ONE declare module 'lib-name' in that file, and 'lib-name' must exactly match the library name (can be found in its package.json, "name" property).

另一方面,如果一个第三方库已经有定义文件.d.ts,并且我们想扩展它的功能,那么我们可以把我们创建的另一个文件中的附加定义.这称为扩充.

On the other hand, if a 3rd-party library already has definition file .d.ts included, and we want to extend its functionalities, then we can put the additional definition in another file that we create. This is called 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 '...' { ... }

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

I leave my discovery here just in case somebody has same question. And please correct me if I missed something.

这篇关于出现错误“模块‘名称’解析为无类型模块在……";编写自定义 TypeScript 定义文件时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆