缩小 TypeScript ‘shape.radius’ 可能是 ‘undefined’。

huangapple go评论66阅读模式
英文:

narrowing typescript 'shape.radius' is possibly 'undefined'

问题

You're getting two "is possibly 'undefined'" errors because TypeScript is not able to infer that the properties shape.radius and shape.sideLength are guaranteed to be defined when you access them in your return statements.

Even though you've used Object.hasOwn and in to check if the properties exist, TypeScript's type checking is still conservative and assumes that these properties might not exist under certain conditions.

To address these errors, you can add non-null assertions (!) to explicitly tell TypeScript that you've already checked for the existence of these properties, like this:

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

By adding (shape.radius as number) and (shape.sideLength as number), you are essentially telling TypeScript that you are confident these properties are of type number and not undefined.

This should resolve the TypeScript errors in your code.

英文:
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) {
    // 'shape.sideLength' is possibly 'undefined'. ts(18048)
    return shape.sideLength**2;
  }
  return undefined;
}

why am i getting 2 "is possibly 'undefined'" errors ? what is wrong with this logic? Didn't I already check that the property exists before returning the calculation?

i used Object.hasOwn and in but in both cases the error continued

答案1

得分: 2

你要找的是判别联合。你必须在你的联合成员中有一个共同的属性,这个属性也必须是唯一的,可以用来识别形状。

type Shape =
  | {
      kind: 'circle';
      radius: number;
    }
  | {
      kind: 'square';
      sideLength: number;
    };

Shape转换为这样将解决错误。

playground

英文:

What you are looking for is discriminated union. You have to have a common property in your union members, which is also unique and can be used for identifying shapes.

type Shape =
  | {
      kind: 'circle';
      radius: number;
    }
  | {
      kind: 'square';
      sideLength: number;
    };

Converting Shape to this will resolve the errors.

playground

huangapple
  • 本文由 发表于 2023年6月13日 06:59:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定