// *** before: ***
interface Circle { kind: "circle"; radius: number; }
interface Square { kind: "square"; side: number; }
function area(shape: Circle | Square) {
const isCircle = shape.kind === "circle";
if (isCircle) {
//shape is still Circle | Square - narrowing did not survive the
//variable
return Math.PI * (shape as Circle).radius ** 2;
}
return (shape as Square).side ** 2;
}
// *** in version 4.4: ***
function areaNarrowed(shape: Circle | Square) {
const isCircle = shape.kind === "circle";
if (isCircle) {
return Math.PI * shape.radius ** 2; // shape is narrowed to Circle
}
return shape.side ** 2; // shape is narrowed to Square
}