首页 > 解决方案 > React Typescript 没有给出类型检查错误

问题描述

我在使用 React 时遇到了一个奇怪的问题,其中 TypeScript 在运行npm startnpm build. 下面是我的代码示例,其中我为函数参数和变量分配了无效值。这段代码没有错误,它编译得很好,即使它应该失败。我最近将 react-scripts 从 v3 升级到 v4,这是我能想到的唯一可能导致此问题的原因。我正在使用 JS 和 TS 的混合。

export default function myFunction(
  value: Function = 100,
) {
    const test: string = 123
}

我确实收到警告,但没有错误:

Line 31:9:  'test' is assigned a value but never used  @typescript-eslint/no-unused-vars

来自 package.json 的包版本

"react-scripts": "^4.0.3",
"typescript": "^4.2.3",

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-jsx",
    "baseUrl": "src",
    "noFallthroughCasesInSwitch": true
  },
  "include": [
    "src"
  ]
}

有没有人有任何见解?

标签: reactjstypescript

解决方案


所以不知何故,TypeScript 在我的开发过程中又开始工作了。奇怪的是,在最初的几次编译之后它仍然无法正常工作,然后突然开始工作。¯_(ツ)_/¯

我最近做的事情是

  • 删除 node_modules 并重新安装
  • 删除我的 tsconfig 然后让 CRA/TypeScript 生成一个新的

我的 TypeScript 版本也降级了。我不确定我是否这样做或 npm 是否这样做。

"react-scripts": "^4.0.3",
"typescript": "^4.1.3",

这是我的新 tsconfig.json

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


推荐阅读