TypeScript: Typing Dynamic Objects and Subsets with Generics

How to use keyof, in, and extends keywords to type dynamic functions in TypeScript

Ross Bulat

--

TypeScript gained popularity over 2020 and is now in the upper bracket of the programming salary range. If you are a JavaScript developer you have most likely been exposed to TypeScript in some project you have worked on.

This article, along with others surrounding it, will introduce the reader to advanced TypeScript concepts by explaining them from the ground up with a typical use case — working with objects and subsets of those objects in a dynamic way such that we do not know the exact structure of these objects, but want to define them without compromise.

Being able to define generic types that successfully type objects without compromises is key when working with API responses and event driven applications, whereby the data you receive is filtered and extracted into various components for various functions to handle.

This article focuses on this use case. Instead of working in live environments, we will keep things straightforward by working with simple functions designed to extract properties from objects and return a smaller object of those properties.

The article will gradually build up the complexity of our types with 3 sections:

  • Basic: How to use primitive types with a pick function — a function designed to return a subset of an object’s properties that correspond with the keys provided. The issues with such basic typing will be presented.
  • Intermediate: TypeScript keyword keyof will be explored with generics to enhance our types to coincide with the object properties to be returned by our function.
  • Advanced: We’ll delve deeper by enhancing the pick return type to only include properties being picked out from the object in question. We will be using the extends and in keywords to achieve this.

The examples created in this piece may be achievable via TypeScript’s built-in Utility Types, which will be a subject of another article. The purpose of this piece is to get the reader familiar with common TypeScript features and understanding how to implement them.

--

--

Ross Bulat

Programmer and Author. @ Parity Technologies, JKRB Investments