0

tsconfig.json: { "compilerOptions": { "strict": true, "lib": ["ES2022"], "exactOptionalPropertyTypes": true } }

interface Shape {
  kind: "circle" | "square",
  radius?: number,
  sideLength?: number
}

function getArea(shape: Shape): number | undefined {
  if (shape.kind === "circle" && Object.hasOwn(shape, "radius")) {
    // 'shape.radius' is possibly 'undefined'. ts(18048)
    return Math.PI * shape.radius**2;
  }
  else if (shape.kind === "square" && "sideLength" in shape) {
    return shape.sideLength**2;
  }
  return undefined;
}

const s1: Shape = {kind: 'circle', radius: undefined};  // if i try this
/* Type '{ kind: "circle"; radius: undefined; }' is not assignable to type 'Shape' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
   Types of property 'radius' are incompatible.
   Type 'undefined' is not assignable to type 'number'.ts(2375) */

why this undefined error? What is missing?

komote7665
  • 31
  • 6
  • 'shape.radius' is possibly 'undefined' because `Object.hasOwn` doesn't provide type guarding functionality like `"radius" in shape`. Check [this](https://tsplay.dev/mblY4w) – Eldar Jun 13 '23 at 20:46
  • You already asked this question https://stackoverflow.com/questions/76460781/narrowing-typescript-shape-radius-is-possibly-undefined – pilchard Jun 13 '23 at 21:19
  • also see [Object.hasOwn and hasOwnProperty doesn't narrow TypeScript type as expected](https://stackoverflow.com/questions/76114274/object-hasown-and-hasownproperty-doesnt-narrow-typescript-type-as-expected) and [How to narrow object type with "in" and/or "hasOwnProperty"](https://stackoverflow.com/questions/63833935/how-to-narrow-object-type-with-in-and-or-hasownproperty) – pilchard Jun 13 '23 at 21:20

0 Answers0