【问题标题】:TypeScript not checking for optional arguments compatibilityTypeScript 不检查可选参数的兼容性
【发布时间】:2018-04-13 23:05:33
【问题描述】:

尽管我的tsconfig.json 中有strict: true,但这不会出错:

const a: (b?: string) => string[] =
         (c : string) => c.split(',');
           ^
  should scream in vein

如何让 TypeScript 对此感到恐慌?

软件包版本:

  • 打字稿 2.5.3
  • ts-loader 3.1.1
  • webpack 3.6.0

这是我完整的tsconfig.json

{
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
    "strict": true,
    "noImplicitAny": true,
    "allowJs": true,
    "sourceMap": true,
    "allowSyntheticDefaultImports": false,
    "moduleResolution": "node",
    "noUnusedLocals": true,
    "noUnusedParameters": false,
    "preserveConstEnums": false,
    "removeComments": false,
    "lib": [
      "es5",
      "es6",
      "dom",
      "es2015.core",
      "es2015.collection",
      "es2015.generator",
      "es2015.iterable",
      "es2015.promise",
      "es2015.proxy",
      "es2015.reflect",
      "es2015.symbol",
      "es2015.symbol.wellknown",
      "esnext.asynciterable"
    ]
  },
  "exclude": [
    "node_modules",
    "test",
    ".git"
  ]
}

【问题讨论】:

    标签: typescript types typescript2.0


    【解决方案1】:

    您的设置中发生了一些奇怪的事情。我将 TypeScript 2.6.1 与您的 tsconfig.json 和代码一起使用:

    const a: (b?: string) => any = (b: string) => 1;
    

    因为您打开了strict 标志,其中包括您需要得到错误的两个标志; strictNullChecksstrictFunctionTypes。当我跑步时:

    tsc
    

    我收到消息:

    app.ts(1,7): error TS2322: Type '(b: string) => number' is not assignable to type '(b?: string | undefined) => any'.   Types of parameters 'b' and 'b' are incompatible.
        Type 'string | undefined' is not assignable to type 'string'.
          Type 'undefined' is not assignable to type 'string'.
    

    你是如何运行编译器的?我问的原因是,如果您如上所示“以普通方式运行”,它只会使用您的配置文件。例如,如果您传递文件名参数,您将不会使用您的配置:

    tsc app.ts
    

    不会出现错误,因为您不再使用 tsconfig.json

    【讨论】:

    • 看来我的TS版本不好。 2.6.1 的 TS 恐慌就好了:}
    猜你喜欢
    • 2018-07-29
    • 1970-01-01
    • 2020-12-11
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多