Type Guards

Discover the world of IT

Type Guards

A type guard offers a similar behavior known from “instanceOf” and “typeOf”, which are in fact typescripts build-in type guards. However, these are limited to certain scopes, limiting the instanceOf to only compare if the class is an instance of another class. Additionally, “typeOf” only can compare simple data types such as strings, numbers, booleans and objects excluding classes, interfaces types, and other more complex data types.

Custom type guards are therefore a good practice to apply when the structure of an object has to be compared with another, making your code a bit more reliable.

The code below illustrates a simple type guard that determines the type, between two different types that shares nearly the same syntax, however, distinguished in one way, just to provide a very simple example of how a type guard can be created.

This function would then be applied whenever such a determination is required similar to the use-cases for “instanceOf” and “typeOf”.

Note that the example specifies both that the type of AB has B and should not have a C, expressing this ensures that the two types are compared properly, leaving the should not have C out of the comparison would work in this scenario, however at some point one might update object AC to ABC and now ABC would contain a B thereby ruin the type guard and potentially your code. As the code could keep function as ABC includes all the members of AB, the type guard is no longer valid. Therefore when using it like so it is important to compare as many factors as possible, to ensure that the type guards work even as the code evolves.

export  type AB = {
  A: string;
  B: string;
}

export  type AC = {
  A: string,
  C: string
}

export  function isA(ABC: AB | AC): ABC is AB {
  // ABC has a B and ABC has no C it must be AB
  return !!(ABC as AB).B && !(ABC as AC).C;
}

Leave a Reply

Your email address will not be published. Required fields are marked *