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)}`);
}
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-10-21 11:00:00 +0000
Seen: 19 times
Last updated: May 05 '21
How can one ensure that sub-classes have uniform method parameters in TypeScript?
Can a TypeScript definition for icon names be provided in MaterialCommunityIcons for React Native?
How can I deal with Expression.Error related to a column in Power Query?
How can you implement pagination in Oracle for the LISTAGG() function?
What is the process for implementing a FutureBuilder on an OnTap function in Flutter?
How can we require users to be logged in before they can access the root folders in WordPress?
In SCSS, what is the method for grouping and reusing a set of classes and styles?