In TypeScript, type guards allow you to narrow down the type of a variable that might be one of several types. Here is the correct way to implement type guards:
interface Circle {
kind: "circle";
radius: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
type Shape = Circle | Rectangle;
function isCircle(shape: Shape): shape is Circle {
return shape.kind === "circle";
}
function isRectangle(shape: Shape): shape is Rectangle {
return shape.kind === "rectangle";
}
function getArea(shape: Shape): number {
if (isCircle(shape)) {
return Math.PI * shape.radius ** 2;
} else if (isRectangle(shape)) {
return shape.width * shape.height;
} else {
return assertNever(shape);
}
}
Note that in the above example, the assertNever
function is used to ensure that all the possible types of the variable have been handled. Here's the implementation of the assertNever
function:
function assertNever(shape: never): never {
throw new Error(`Unexpected shape: ${JSON.stringify(shape)}`);
}
Asked: 2022-10-21 11:00:00 +0000
Seen: 21 times
Last updated: May 05 '21