Working around a bad index.d.ts file provided by npm package

时间:2019-03-17 22:35:51

标签: typescript definitelytyped

I recently encountered an npm package that wasn't written in TypeScript but did provide its own index.d.ts file. Unfortunately, these types were inaccurate and contributed by someone who wasn't maintaining the package. When I add a /// <reference... directive to point to my fixed types, VS Code seems unsure of what to do and informs me that there are two type definitions for the given objects. I can't move on while this is unresolved. What's my move here to get working other than editing the file in node_modules on my machine?

If these types were provided by DefinitelyTyped, this would be easy: I'd just remove the bad ones, submit a PR with my changes, use my local version in the meantime. Since this index.d.ts is part of the library itself, is my only option to clone the whole repo, work from that, submit a PR when I'm ready, hope they merge and release a new version quickly? That doesn't seem right. Is there a way to tell the compiler to ignore a specific index.d.ts file in node_modules so mine is the only one?

2 个答案:

答案 0 :(得分:1)

Add skipLibCheck: true in the compilerOptions in the tsconfig.json file. This disables the type checking for all *.d.ts files.

The flag is described in the compiler options documentation.

Another option if you are sure your code is correct is to ignore the errors by using // @ts-ignore comments on the lines where you get errors.

Here is also a link to a similar post that offers also two possible solutions.

答案 1 :(得分:0)

@AlesD在另一个答案的评论中链接的评论here完美地解决了问题。在src中,创建node_modules/problem-library/index.d.ts并将更新的类型定义放在此处。它们将覆盖库提供的内容。

您的.gitignore文件可能会忽略您的文件,这不好。你可以解决 通过修改您的.gitignore

node_modules/
!src/node_modules/

第一个是您对该文件夹的现有排除,第二个添加了一种针对这种情况的否定模式。