编写自定义 TypeScript 定义文件时出现错误 "Module 'name' resolves to an untyped module at..."

Having error "Module 'name' resolves to an untyped module at..." when writing custom TypeScript definition file

我找不到我安装的 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] 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.

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

更新:

我正在使用:

经过一些尝试和错误,我发现augmentation表示"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" 属性 中找到)。

另一方面,如果第 3 方库 已经包含定义文件 .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 '...' { ... }

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

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

导入应该在内部模块声明中声明。

示例:

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

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

我遇到的问题是我试图在 .ts 文件中声明模块。我将其更改为 .d.ts,一切正常。