英文:
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
转换为这样将解决错误。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论