简体   繁体   English

调用可为空的 function 时 Typescript 不会引发错误

[英]Typescript throws no error when calling nullable function

I have the following code in my react app:我的反应应用程序中有以下代码:

在此处输入图像描述

As you can see onCheck can be undefined .如您所见onCheck可以是undefined but typescript shows no error and I'm getting a runtime error.但 typescript 没有显示错误,我收到运行时错误。

I have to add this prop has no default value.我必须添加这个道具没有默认值。

My tsconfig:我的 tsconfig:

{
    "compileOnSave": false,
    "compilerOptions": {
        "sourceMap": true,
        "target": "es5",
        "module": "esnext",
        "declaration": false,
        "noImplicitAny": false,
        "experimentalDecorators": true,
        "noLib": false,
        "jsx": "react",
        "noEmitOnError": true,
        "moduleResolution": "node",
        "lib": [
            "DOM",
            "ES5",
            "ScriptHost",
            "ES2015",
            "ES2018.Promise"
        ],
        "allowSyntheticDefaultImports": true
    },
    "exclude": [
        "node_modules"
    ]
}

Under compilerOptions , add "strict": true in your tsconfig.json .compilerOptions下,tsconfig.json中添加"strict": true

From the docs:从文档:

The strict flag enables a wide range of type checking behavior that results in stronger guarantees of program correctness.严格标志启用了范围广泛的类型检查行为,从而更有效地保证了程序的正确性。 Turning this on is equivalent to enabling all of the strict mode family options, which are outlined below.打开它相当于启用所有严格模式系列选项,如下所述。

  • alwaysStrict
  • strictNullChecks
  • strictBindCallApply
  • strictFunctionTypes
  • strictPropertyInitialization
  • noImplicitAny
  • noImplicitThis

If you only care about the nullable variables, then just use the "strictNullChecks" flag .如果您只关心可空变量,那么只需使用"strictNullChecks"标志

You don't have the according compiler option set in your tsconfig.json您没有在tsconfig.json中设置相应的编译器选项

Either add要么添加

"strictNullChecks": true

to just enable the null checks, or (recommended) add仅启用null检查,或(推荐)添加

"strict": true

to add a wide range of checks.添加范围广泛的检查。

Be aware that using "strict": true may break your build when you upgrade the typescript version.请注意,当您升级 typescript 版本时,使用"strict": true可能会破坏您的构建。 Because new strict... flags will be switched on with that flag automatically.因为新的strict...标志将自动使用该标志打开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM