VSCode 在 .tsx 文件中使用 AS 关键字显示类型断言错误

VSCode showing error on type assertion using AS keyword in .tsx file

VSCode 在 .tsx 文件中使用 AS 关键字显示类型断言错误。而当我在网络浏览器上执行代码和 运行 应用程序时没有问题。

解析错误:意外标记,应为“;”

我的eslint.rc

{
  "parser": "babel-eslint",
  "env": {
    "es6": true,
    "browser": true
  },
  "extends": [
    "airbnb-typescript",
    "airbnb/hooks",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:mdx/recommended"
  ],
  "settings": {
    "import/resolver": {
      "node": {
        "paths": [
          "src"
        ],
        "extensions": [
          ".js",
          ".jsx",
          ".ts",
          ".tsx",
          ".mdx"
        ]
      }
    }
  },
  "rules": {
    "comma-dangle": "off",
    "import/no-unresolved": "off",
    "jsx-a11y/anchor-is-valid": "off",
    "jsx-a11y/click-events-have-key-events": "off",
    "jsx-a11y/control-has-associated-label": "off",
    "jsx-a11y/no-static-element-interactions": "off",
    "no-console": "off",
    "no-plusplus": "off",
    "react-hooks/exhaustive-deps": "off",
    "react/forbid-prop-types": "off",
    "react/jsx-filename-extension": "off",
    "react/jsx-props-no-spreading": "off",
    "react/require-default-props": "off"
  }
}

我的tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "strictNullChecks": false,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "sourceMap": true, // Generate corresponding .map file
    "declaration": true, // Generate corresponding .d.ts file
  },
  "include": [
    "src/**/*" // *** The files TypeScript should type check ***
  ],
  "exclude": ["node_modules", "build"] // *** The files to not type check ***
}

我的开发依赖项:

"devDependencies": {
    "@typescript-eslint/eslint-plugin": "^2.34.0",
    "@typescript-eslint/parser": "^2.34.0",
    "eslint": "^6.8.0",
    "eslint-config-airbnb": "^18.2.0",
    "eslint-config-airbnb-typescript": "^7.2.1",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-import": "^2.22.0",
    "eslint-plugin-jsx-a11y": "^6.3.1",
    "eslint-plugin-mdx": "^1.7.1",
    "eslint-plugin-prettier": "^3.1.4",
    "eslint-plugin-react": "^7.20.3",
    "eslint-plugin-react-hooks": "^2.5.1",
    "mdx-loader": "^3.0.2",
    "numeral": "^2.0.6",
    "prettier": "^1.19.1",
    "typescript": "^3.9.7"
  }

经过一番研发,我已经解决了这个问题。问题是 .eslintrc 中使用的解析器是 "parser": "babel-eslint" 而我们在 react "parser" 中使用 typescript 时应该使用这个解析器: "@typescript-eslint/parser"

为此你必须安装 @typescript-eslint/parser 包作为 devDependencies。

vscode 现在没有显示错误: