簡體   English   中英

typescript strictNullChecks 在手冊 getArea 上返回 undefined Function

[英]typescript with strictNullChecks returning undefined on handbook getArea Function

我正在運行 typescript 手冊中的一個示例,我的 function 返回未定義,即使啟用了 stricNullChecks。 我覺得編譯的時候應該報錯,但是這次編譯沒有問題,function返回undefined。

代碼:

interface Circle {
    kind: "circle";
    radius: number;
}
interface Square {
    kind: "square";
    sideLength: number;
}
type Shape = Circle | Square;

function getArea(shape: Shape) {
    switch (shape.kind) {
        case "circle":
            return Math.PI * shape.radius ** 2;
    }
}

let mysquare: Shape = {kind: 'square', sideLength: 10}

console.log(getArea(mysquare))

我的配置文件:

{
    "extends": "@tsconfig/node16/tsconfig.json",
    "compilerOptions": {
        "noImplicitAny": true,
        "strictNullChecks": true,
        "sourceMap": true,
        "types": ["node"],
      "lib": [
        "dom"
      ]
    },
  "exclude": [
    "node_modules"
  ]
}

我的 package.json:

{
  "devDependencies": {
    "@tsconfig/node16": "^1.0.3",
    "@types/node": "^18.7.23"
  }
}

也許我正在使用我的環境來處理 typescript,或者它應該返回未定義而我沒有得到這里的東西?

您還需要noImplicitReturns

啟用后,TypeScript 將檢查 function 中的所有代碼路徑以確保它們返回值。

啟用它后,您將看到getArea的錯誤,正如您所希望的那樣:

function getArea(形狀:形狀):數字 | 不明確的

並非所有代碼路徑都返回值。(7030)

暫無
暫無

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

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