Typescript - Tips & Tricks - Type Guard

There are some cases, where we need to detect the type of the object to get the correct...

#typescript#webdev
Luca Del PuppoLuca Del Puppo
Article Series · Part 16 of 21TypeScript - Tips & Tricks
View full series (21)
  1. #15Previous
    Assert Function
  2. #16Reading now
    Type Guard
  3. #17Up next
    Conditional Type
Browse all 21 parts in this series
  1. #1typeof
  2. #2Literal Types
  3. #3keyof
  4. #4Union and Intersection
  5. #5Overloaded Functions
  6. #6this parameter
  7. #7any vs. unknown
  8. #8Optional modifier
  9. #9Index Signature
  10. #10readonly modifier
  11. #11Readonly Array
  12. #12Tuple
  13. #13Non-null assertion operator
  14. #14Never type
  15. #15Assert Function
  16. #16Type GuardCurrent
  17. #17Conditional Type
  18. #18infer keyword
  19. #19Mapped Types
  20. #20Advanced Types
  21. #21Rest Parameters & Rest Arguments

There are some cases, where we need to detect the type of the object to get the correct implementation of our method. Let me show you a case

type Square = {
  size: number;
};

type Rectangle = {
  with: number;
  height: number;
};

type Circle = {
  radius: number;
};

type Shape = Square | Rectangle | Circle;

const area = (shape: Shape) => {
  if ("size" in shape) return shape.size * shape.size;
  if ("with" in shape) return shape.with * shape.height;
  if ("radius" in shape) return shape.radius * 2 * Math.PI;
};

In this case, in the area method, we need to detect the type of the shape to return the correct result. Here we detect the type of the shape in the if condition but typescript permits us to create a special function that identifies if a type is of a specific type or not. These functions are created to have Type Guards that help the compiler, the intellisense, and us to understand the correct type of the object. To show you this function in action, the previous example can be rewritten in this way.

Square = {
  size: number;
};

type Rectangle = {
  with: number;
  height: number;
};

type Circle = {
  radius: number;
};

type Shape = Square | Rectangle | Circle;

function isSquare(shape: Shape): shape is Square {
  return "size" in shape;
}

function isRectangle(shape: Shape): shape is Rectangle {
  return "with" in shape;
}

function isCircle(shape: Shape): shape is Circle {
  return "radius" in shape;
}

const area = (shape: Shape) => {
  if (isSquare(shape)) return shape.size * shape.size;
  if (isRectangle(shape)) return shape.with * shape.height;
  if (isCircle(shape)) return shape.radius * 2 * Math.PI;
};

As you can see, the methods: isSquare, isRectangle, and isCircle get a shape as parameter and return a boolean value. If the result is true the shape parameter corresponds to the type indicated to the right of the is keyword, otherwise, it corresponds to another type.

I hope this feature will help you in the future and improve the reading of your code.

It’s all Guy! See you soon!

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.