Home > OS >  typescript with strictNullChecks returning undefined on handbook getArea Function
typescript with strictNullChecks returning undefined on handbook getArea Function

Time:09-29

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?

CodePudding user response:

You also need noImplicitReturns:

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)

  • Related