TypeScript:当外部函数返回“any”类型时显示错误?

Lia*_*iam 5 any typescript

例如,该函数JSON.parse(data)返回 的类型any。所以如果你写这样的东西:

const parsed = JSON.parse('example');

console.log(parsed.somethingThatDoesntExist);
Run Code Online (Sandbox Code Playgroud)

尽管在 my 中noImplicitAny设置为,并且 my有规则,但 VSCode 中没有发生错误。truetsconfig.json.eslintrc.js'@typescript-eslint/no-explicit-any': 'error'

我还尝试将以下规则添加到我的 中eslintrc.js,但是它们似乎破坏了所有 TypeScript 错误检查:

'@typescript-eslint/no-unsafe-call': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
Run Code Online (Sandbox Code Playgroud)

在理想的世界中,我希望这any被假定为unknown,但错误也很大。

这是我的eslintrc.js

module.exports = exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  parserOptions: {
    ecmaVersion: 2021,
  },
  extends: ['plugin:@typescript-eslint/recommended', 'prettier', 'plugin:prettier/recommended'],
  rules: {
    '@typescript-eslint/ban-ts-comment': 'off',
    '@typescript-eslint/no-unsafe-call': 'error',
    '@typescript-eslint/no-unsafe-member-access': 'error',
    '@typescript-eslint/no-unsafe-argument': 'error',
    '@typescript-eslint/no-unsafe-assignment': 'error',
    '@typescript-eslint/no-explicit-any': 'error',
    'prettier/prettier': [
      'error',
      {
        trailingComma: 'all',
        tabWidth: 2,
        semi: true,
        singleQuote: true,
        bracketSpacing: true,
        printWidth: 120,
        endOfLine: 'auto',
      },
    ],
  },
};

Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
  "compilerOptions": {
    "strict": true,
    "target": "es6",
    "module": "commonjs",
    "lib": [
      "es6",
      "ES2021.String"
    ],
    "esModuleInterop": true, 
    "moduleResolution": "node",
    "outDir": "../build/",
    "rootDir": ".",
    "resolveJsonModule": true,
    "composite": true,
    "types": [],
    "noImplicitAny": true,
    "noImplicitThis": true,
    "noImplicitReturns": true
  }
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*ong 1

我认为最好的选择是覆盖任何需要显式类型的库。一般来说,内置函数的类型很好(JSON.parse 除外),但是如果您想修复外部库中损坏或存根的类型,这可能会很有帮助。

对于全局(或内置)global.d.ts

declare global {
  interface JSON {
    parse<T>(text: string, reviver?: (this: any, key: string, value: any) => T): T
  }
}

export {} //this is needed to make it a module
Run Code Online (Sandbox Code Playgroud)

或者模块的不同语法

declare module 'fooLibrary' {
  declare function bar<T>(): T
}
// IE. require('fooLibrary') or import * from ('fooLibrary')
Run Code Online (Sandbox Code Playgroud)

现在当你尝试使用JSON.parse

const foo = JSON.parse('test');
//   ^type? => unknown
const bar = JSON.parse<Record<string, any>>(...);
//   ^type? => Record<string, any>
Run Code Online (Sandbox Code Playgroud)

查看 TS Playground 上的工作示例