TypeScript Generics and Type Guards - Explained by Example

Uduak Obong-Eren
The Startup
Published in
8 min readApr 1, 2020

--

How we built a robust utility function using TypeScript’s powerful features

Photo by Andrew Friedrich on Unsplash

TypeScript has some powerful features that enable easy building of scalable JavaScript applications. This article describes how we leveraged two TypeScript features: generics and type guards in writing a robust utility function.

How a utility function was born

If you had to write logic to check if an object of a certain type is defined and if the object actually has any keys, a simple way to do it in TypeScript would be:

If you had to use this logic repeatedly, an ideal thing to do would be to create a function that encapsulates this logic. Written in TypeScript, this function would look something like:

--

--

Uduak Obong-Eren
The Startup

Software Engineer | Open Source Enthusiast | CMU Alum | I write about web and mobile technologies as well as professional and personal well-being