// Object unions with variants of a similiar property, but different
// key names. Need to add a common property to connect them.
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
type Shape = Circle | Square;
// TypeScript can now narrow out the members
function getArea (shape: Shape) {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2 // safely accessing shape.radius
}
}
// Alternatively use a switch statement
switch(shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2
case 'square':
return shape.sideLength ** 2