【问题标题】:TypeScript compiler not throwing error when expected in my projectTypeScript 编译器在我的项目中没有按预期抛出错误
【发布时间】:2021-12-01 10:07:44
【问题描述】:

我在我的一个项目中遇到了一些麻烦,TypeScript 编译器没有在我期望的时候抱怨类型不匹配。当我在 TS 操场上尝试相同的代码块时,它确实会抱怨,正如我所料。不确定我的项目配置是否有问题 - 我没有注意到我的项目中有任何其他类似的问题。

这是有问题的示例代码:

const func = (opt: { a: number; b: number; c: number }) => undefined;
const func2 = (arg: (opt: { a: number; b: number }) => undefined) => undefined;
func2(func);

这是在 Playground 中导致错误的相同代码:

https://www.typescriptlang.org/play?ts=4.3.5#code/MYewdgzgLgBAZgVzMGBeGAKEAHKAuGAbxgEMCwEBbAIwFMAnAbhmvKrqZmDZoZgF8AlGgB8MJABNacAJZhaExgChQkWImQAmNJhL0A5gSy4CxMjAq9OrC+z5DR4sFNnyJw1GMnS5C5RuBNDADBZSA

这是我的tsconfig.json

{
  "compilerOptions": {
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "allowJs": false,
    "moduleResolution": "node",
    "lib": [ "es2015" ],
    "experimentalDecorators": true,
    "useDefineForClassFields": true,
    "downlevelIteration": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": true,
    "outDir": "./dist/",
    "baseUrl": "./src",
    "paths": {
      "@lib/*": ["../../lib/src/*"], // relative to baseUrl
    },
    "lib": [ "dom" ],
    "jsx": "react",
  },
  "types": [
    "babylonjs"
  ],
  "typeRoots": [
    "./node_modules/@types"
  ],
  "plugins": [
    {
      "name": "typescript-plugin-css-modules"
    }
  ]
}

我在我的项目中使用 TypeScript 版本 4.3.5

【问题讨论】:

    标签: typescript compiler-errors


    【解决方案1】:

    您无需激活strictFunctionTypes 标志。

    启用后,此标志会导致更正确地检查函数参数。

    另外,值得使用strict: true

    strict 标志支持范围广泛的类型检查行为,从而增强了程序正确性的保证

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      • 2016-06-19
      • 2016-09-11
      相关资源
      最近更新 更多