Ask Your Question
3

What is the correct way to implement type-guard?

asked 2022-10-21 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-05-05 11:00:00 +0000

bukephalos gravatar image

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)}`); 
}
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-10-21 11:00:00 +0000

Seen: 19 times

Last updated: May 05 '21