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?