Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

How I Reduce Type Complexity in TypeScript with 3 Clear-cut Steps

Greg Pabian
Level Up Coding
Published in
8 min readApr 28, 2024

--

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.

Photo by Robert Zunikoff on Unsplash

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.

Created using Excalidraw
An identity element for adding integers visualized. Created using Excalidraw.

Similarly, the identity element for multiplying integers is one.

The identity element for multiplying integers visualized. Created using Excalidraw.

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.

--

--

Responses (13)

Write a response