Recursion in Mapped Types: Making Nested Properties Optional in TypeScript

Let’s talk about something that makes TypeScript feel almost like a programming language at the type level - 'Recursion in Mapped Types.' Imagine you have a deeply nested object type. Some properties are objects. Some are objects inside objects. Some are arrays of objects. Now your task is simple in words - 'Make everything optional. Even nested properties.' At first, this feels easy. We already know about 'Partial<T>' utility type. But 'Partial' only works at the first level. It does not go deep. Nested properties remain required. So how do we make everything optional at every level? This is where recursion comes in. In normal programming, recursion means a function calls itself. In TypeScript types, recursion means a type references itself inside its own definition. That’s it. So, how do we solve the problem with a deeply nested object? We can define a type that iterates over each property of an object, makes it optional, and if the property itself is an object, apply the same logic again. This 'apply the same logic again' part is recursion. But how does this even work? Here’s something fascinating about TypeScript. When a mapped type is applied to a primitive type like string or number, TypeScript simply returns that primitive type. It does not try to iterate over it. This behavior is intentional and baked into the type system. That’s why recursive mapped types don’t break when they eventually reach primitive properties. For example, when recursion hits 'string', it just stops naturally. That’s elegant. Recursion in mapped types is where TypeScript stops being static typing, and starts feeling like a type transformation engine. #Programming #TypeScript #JavaScript #WebDevelopment #Coding

  • text

To view or add a comment, sign in

Explore content categories