如何允许缺少.d.ts类型定义的模块?

4
我正在使用一些不太流行的模块,例如 Dyojs-sha3,它们似乎没有任何类型。
我现在并不关心第三方库中的类型,我不想花费数小时来输入这些内容。我主要用它来限制服务器上的错误,并在开发过程中使故障排除更加容易。
之前我遇到了一个 Cannot find module X 错误,所以我在我的 tsconfig.json 文件中添加了:"moduleResolution": "node"
如何让 TypeScript 不抱怨缺少类型的节点模块?
整个错误信息:
Could not find a declaration file for module 'dyo'. '/node_modules/dyo/dist/dyo.umd.js' implicitly has an 'any' type.
  Try `npm install @types/dyo` if it exists or add a new declaration (.d.ts) file containing `declare module 'dyo';` [7016]

我在网络的某个角落找到了一个注释中的// @ts-nocheck,但它似乎不起作用。

我能通过模块关闭它吗?

2个回答

8
你可以创建虚拟的.d.ts定义,允许从模块中导入任何内容 - 导入它将导致dyo具有any类型(导入方式的确切方法取决于esModuleInterop编译器设置以及从dyo.umd.js导出的方式)。
  1. create a file dyo.d.ts somewhere within your project with one line in it

    declare module 'dyo';
    
  2. in a file that references that module, add this line at the top, with appropriate path to dyo.d.ts file:

    /// <reference path='./dyo.d.ts' />
    

替代方案2是在tsconfig.json文件中将dyo.d.ts添加到编译包含文件列表中:

"files": [
    ... other files as necessary ...

    "./path/to/dyo.d.ts"
]

我选择了“文件”方法,以避免修改模块文件,在后续更新中可能会出现故障。谢谢! - HypeWolf

-1
对于不想创建自己的.d.ts定义文件的人,您可以在tsconfig.json中使用"noImplicitAny": false来允许使用没有TypeScript定义文件的外部库。
例如:
{
  "compileOnSave": false,
  "compilerOptions": {
     ...
    "noImplicitAny": false,
     ...
    }
  }
}

这使得TypeScript可以从每个缺失的类型中推断出any类型,因此这也会影响到您自己的项目。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接