TypeScript Generics and Type Guards - Explained by Example
How we built a robust utility function using TypeScript’s powerful features
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: