簡體   English   中英

調用可為空的 function 時 Typescript 不會引發錯誤

[英]Typescript throws no error when calling nullable function

我的反應應用程序中有以下代碼:

在此處輸入圖像描述

如您所見onCheck可以是undefined 但 typescript 沒有顯示錯誤,我收到運行時錯誤。

我必須添加這個道具沒有默認值。

我的 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"
    ]
}

compilerOptions下,tsconfig.json中添加"strict": true

從文檔:

嚴格標志啟用了范圍廣泛的類型檢查行為,從而更有效地保證了程序的正確性。 打開它相當於啟用所有嚴格模式系列選項,如下所述。

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

如果您只關心可空變量,那么只需使用"strictNullChecks"標志

您沒有在tsconfig.json中設置相應的編譯器選項

要么添加

"strictNullChecks": true

僅啟用null檢查,或(推薦)添加

"strict": true

添加范圍廣泛的檢查。

請注意,當您升級 typescript 版本時,使用"strict": true可能會破壞您的構建。 因為新的strict...標志將自動使用該標志打開。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM