首页 > 解决方案 > TypeScript 强制转换运算符“as”上的 ESlint 解析错误“Unexpected token”

问题描述

任何出现的as运算符都会[eslint] [E] Parsing error: Unexpected token, expected ";"指向 的位置as。示例代码:

{error && <small className="invalid-feedback">{(error as any).message}</small>}

此转换为'函数any中某些错误的解决方法。react-hooks-formuseFormContext

当我忽略错误并编译应用程序时,它工作正常。

这发生在使用最新 TypeScript 和 react-scripts 的标准未弹出 Create React App 中:

$ npm list -dev -depth 0
frontend@0.1.0 
├── eslint-plugin-flowtype@3.13.0
├── react-hot-loader@4.12.19
├── react-scripts@3.4.0
└── typescript@3.8.2

AFAIK 除了自动生成之外没有配置文件tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

任何想法为什么会发生这种情况?

标签: reactjstypescripteslint

解决方案


我遇到了类似的问题,一个对我有用的简单修复方法如下。
我将此添加到我的package.json

  "eslintConfig": {
    "extends": [
      "react-app"
    ]
  },

我注意到它会在其中create-react-app --template typescript生成一个package.json


推荐阅读