Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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:

  1. Define the different types that the variable can hold.
interface Circle {
  kind: "circle";
  radius: number;
}

interface Rectangle {
  kind: "rectangle";
  width: number;
  height: number;
}

type Shape = Circle | Rectangle;
  1. Create a function that checks the type of the variable.
function isCircle(shape: Shape): shape is Circle {
  return shape.kind === "circle";
}

function isRectangle(shape: Shape): shape is Rectangle {
  return shape.kind === "rectangle";
}
  1. Use the type guard to narrow down the type of the variable.
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)}`); 
}