简体   繁体   中英

typescript with strictNullChecks returning undefined on handbook getArea Function

I am running through one example from the typescript handbook and my function is returning undefined even with stricNullChecks enabled. I feel that I should get an error when compiling, but this compile without problems and the function returns undefined.

The code:

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))

My tsconfig:

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

My package.json:

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

Maybe I am working against typescript with my environment, or it should return undefined and I am not getting the thing here?

You also neednoImplicitReturns :

When enabled, TypeScript will check all code paths in a function to ensure they return a value.

With it on, you'll see the error for getArea , as you're hoping for:

function getArea(shape: Shape): number | undefined

Not all code paths return a value.(7030)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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