Member-only story
How I Reduce Type Complexity in TypeScript with 3 Clear-cut Steps
Have you ever come across a TypeScript project too hard to comprehend? Did you ever wonder why that happened or how you could prevent it from happening? I have answers to both of these questions.
Over the last couple of years, I spent significant time on reducing code complexity in TypeScript projects. Contrary to the popular argument, indiscriminate usage of TypeScript features over JavaScript may convolute a codebase, especially when tried by inexperienced engineers. I would love to show you my ideas for reducing type complexity based on my experience.
Identity Elements
Have you ever spotted nullable function parameters? Dealing with nullability requires adding checks throughout the function, including optional chaining (?.
), null coalescing operators (??
), and assignments (??=
). Whoever reads such a function later will likely focus on language elements instead of the business logic!
Fortunately, there exists a solution.
If you were paying attention to your algebra classes, you are likely familiar with the concept of identity (neutral) elements for binary operations.
If we have a binary operation within a particular domain, an identity element used as one operand never changes the other. Naturally, the identity element must belong to the domain.
For instance, the identity element for adding integers is zero.

Similarly, the identity element for multiplying integers is one.

How do we use this particular theory in practice?
Imagine we want a function that calculates the average salary of people in a particular department in different companies. We look up the people using an external API. The API returns null
instead of a list of nonexistent departments in a company.