TypeScript不检查可选参数兼容性

时间:2017-11-01 15:16:55

标签: typescript types typescript2.0

虽然我strict: true中有tsconfig.json,但这并非错误:

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

如何让TypeScript对此感到恐慌?

包版本:

  • 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"
  ]
}

1 个答案:

答案 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

相关问题