打字稿通过配置忽略特定文件中的错误

Mar*_*rek 9 npm node-modules typescript

是否可以通过以下方式忽略特定文件中的打字稿错误tsconfig.json?我知道有他们网站exclude上描述的财产,但这不是我要找的。就像声明的那样:

如果文件 B.ts 被另一个文件 A.ts 引用,则不能排除 B.ts,除非在“排除”列表中也指定了引用文件 A.ts。

当你使用某个 npm 包时,它总是会被打字稿检查是非常合乎逻辑的。即使你努力到exclude整个node_modules或只是特定的一个。你会失败的。因此,如果某些节点模块文件中存在打字稿错误(由于某种原因、过时的类型、版本不匹配等),那么您就被卡住了。

我正在寻找的是一个选项,可以忽略我无法编辑的特定库文件中的打字稿错误。类似于// @ts-nocheck,但在tsconfig.json级别上:

{
  "nocheck": [
    "node_modules/redux-thunk/index.d.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

skipLibCheck编译器选项是不是一个解决方案。我仍然想继续检查其他图书馆。

小智 0

我有办法解决这个问题。如果包中存在一些错误的类型,您可以在项目中添加一个文件,导入错误类型的变量并使用正确的类型导出它,然后使用 typescript 的路径映射来使用您自己的类型而不是包:

node_modules/package/wrongType.js文件:

"use strict";
exports.__esModule = true;
exports.Test = exports.TestFn = void 0;
function TestFn(input) {
    if (typeof input === "string")
        return "string";
    return 2;
}
exports.TestFn = TestFn;
exports.Test = {
    a: "salam",
    b: 2,
    c: TestFn(80)
};
Run Code Online (Sandbox Code Playgroud)

node_modules/package/wrongType.d.ts文件:

export interface TestType {
    a: string;
    b: string;
    c: string;
}
export declare function TestFn(input: any): number;
export declare const Test: TestType;
Run Code Online (Sandbox Code Playgroud)

tsconfig.json文件:

  "compilerOptions": {
    ...
    "paths": {
      "package/wrongType": ["src/components/rightType"]
    }
    ...
Run Code Online (Sandbox Code Playgroud)

src/components/rightType.ts文件:

import { Test as WrongTest } from "package/wrongType";

interface TestType {
  a: string;
  b: number;
  c: number;
}

// @ts-ignore
export const Test: TestType = WrongTest;
Run Code Online (Sandbox Code Playgroud)

现在,任何有import { Test } from "package/wrongType"打字稿的地方都会找到您定义的正确类型,当包修复后,您可以删除您的paths文件rightType,一切都会好起来的。