Skip to main content

Stop Using TypeScript Types This Way - Opt for the Map Pattern Instead


Introduction


While working on a real-life project, I came across a particular TypeScript implementation that was functional but lacked flexibility. In this blog, I’ll walk you through the problem I encountered, and how I improved the design by making a more dynamic approach using the Map pattern.

The problem


I came across this TypeScript type:

// FinalResponse.ts
import { Reaction } from './Reaction'
export type FinalResponse = {
totalScore: number
headingsPenalty: number
sentencesPenalty: number
charactersPenalty: number
wordsPenalty: number
headings: string[]
sentences: string[]
words: string[]
links: { href: string; text: string }[]
exceeded: {
exceededSentences: string[]
repeatedWords: { word: string; count: number }[]
}
reactions: {
likes: Reaction
unicorns: Reaction
explodingHeads: Reaction
raisedHands: Reaction
fire: Reaction
}
}

Additionally, this Reaction type was defined:

// Reaction.ts
export type Reaction = {
count: number
percentage: number
}

And this was being used in a function like so:

// calculator.ts
export const calculateScore = (
headings: string[],
sentences: string[],
words: string[],
totalPostCharactersCount: number,
links: { href: string; text: string }[],
reactions: {
likes: Reaction
unicorns: Reaction
explodingHeads: Reaction
raisedHands: Reaction
fire: Reaction
},
): FinalResponse => {
// Score calculation logic...
}

The Issue with This Approach


Now, imagine the scenario where the developer needs to add a new reaction (e.g., hearts, claps, etc.).
Given the current setup, they would have to:

  • Modify the FinalResponse.ts file to add the new reaction type.
  • Update the Reaction.ts type if necessary.
  • Modify the calculateScore function to include the new reaction.
  • Possibly update other parts of the application that rely on this structure.

So instead of just adding the new reaction in one place, they end up making changes in three or more files, which increases the potential for errors and redundancy. This approach is tightly coupled.

Solution


I came up with a cleaner solution by introducing a more flexible and reusable structure.

// FinalResponse.ts
import { Reaction } from './Reaction'
export type ReactionMap = Record<string, Reaction>
export type FinalResponse = {
totalScore: number
headingsPenalty: number
sentencesPenalty: number
charactersPenalty: number
wordsPenalty: number
headings: string[]
sentences: string[]
words: string[]
links: { href: string; text: string }[]
exceeded: {
exceededSentences: string[]
repeatedWords: { word: string; count: number }[]
}
reactions: ReactionMap
}

Explanation:

  • ReactionMap: This type uses Record<string, Reaction>, which means any string can be a key, and the value will always be of type Reaction.
  • FinalResponse: Now, the reactions field in FinalResponse is of type ReactionMap, allowing you to add any reaction dynamically without having to modify multiple files.

Clean code


In the calculator.ts file, the function now looks like this:

// calculator.ts
export const calculateScore = (
headings: string[],
sentences: string[],
words: string[],
totalPostCharactersCount: number,
links: { href: string; text: string }[],
reactions: ReactionMap,
): FinalResponse => {
// Score calculation logic...
}

But Wait! We Need Some Control


Although the new solution provides flexibility, it also introduces the risk of adding unchecked reactions, meaning anyone could potentially add any string as a reaction. We definitely don’t want that.

To fix this, we can enforce stricter control over the allowed reactions.

More secure solution


Here’s the updated version where we restrict the reactions to a predefined set of allowed values:

// FinalResponse.ts
import { Reaction } from './Reaction'
type AllowedReactions =
| 'likes'
| 'unicorns'
| 'explodingHeads'
| 'raisedHands'
| 'fire'
export type ReactionMap = {
[key in AllowedReactions]: Reaction
}
export type FinalResponse = {
totalScore: number
headingsPenalty: number
sentencesPenalty: number
charactersPenalty: number
wordsPenalty: number
headings: string[]
sentences: string[]
words: string[]
links: { href: string; text: string }[]
exceeded: {
exceededSentences: string[]
repeatedWords: { word: string; count: number }[]
}
reactions: ReactionMap
}

Visual representation


Conclusion


This approach strikes a balance between flexibility and control:

  • Flexibility: You can easily add new reactions by modifying just the AllowedReactions type.
  • Control: The use of a union type ensures that only the allowed reactions can be used, preventing the risk of invalid or unwanted reactions being added.

This code follows the Open/Closed Principle (OCP) by enabling the addition of new functionality through extensions, without the need to modify the existing code.

With this pattern, we can easily extend the list of reactions without modifying too many files, while still maintaining strict control over what can be added.


Comments

Popular posts from this blog

CSS only Click-handlers You Might not be using, but you should

  You’re building a simple website, a good-looking landing page with a “See More” button. Instinctively, you reach for JavaScript to handle the button click event. But wait — what if I told you that CSS alone could do the job? Yes. CSS is often underestimated, but it can handle click interactions without JavaScript. In this guide, you’ll learn how to create CSS-only click handlers using the :target pseudo-class, and explore scenarios where this approach makes perfect sense. The :target Pseudo-Class CSS offers several pseudo-classes that let you style elements based on different states ( :hover , :focus , :checked ). But there’s one you might not have used before —  :target . The :target pseudo-class applies styles to an element when its ID matches the fragment identifier in the URL (the part after # ). This behavior is commonly seen when clicking an anchor link that jumps to a section on the same page. Here’s a simple example : <a href="#contact">Go to Contact</...

Sharpen Your Front-End Skills: Quick HTML, CSS & React Interview Challenges

  The source of this image is Chat GPT based on writing! Are you preparing for front-end developer interviews and looking for practical, hands-on ways to improve your HTML, CSS, and React skills? Whether you’re a beginner aiming to build confidence or an experienced developer brushing up on UI skills, small, targeted challenges can make a huge difference. In this article, I’ll walk you through some of the best free and low-cost resources that offer real-world front-end tasks — perfect for interview prep, portfolio building, and daily practice. 1. Frontend Mentor frontendmentor.io Frontend Mentor is one of the most popular platforms for hands-on HTML, CSS, and JavaScript challenges. You get beautifully designed templates (in Figma or image formats) and are asked to bring them to life using clean code. The platform offers difficulty levels ranging from newbie to expert, and it’s perfect for practicing responsiveness and semantic HTML. Bonus : You can even filter for React-based ...

6 Essential JavaScript Concepts Every Developer Should Understand

It’s the only language I’ve used where [] == ![] it's true and where you can, typeof null and somehow get 'object' . But despite all its quirks (and there are many), there are a few core concepts that make life with JS not just easier, but saner. This isn’t some computer science flex. These are practical concepts that, once you understand them, make you write better, cleaner, and less buggy code. 1. Hoisting  Before you rage at your variables being undefined , understand this: JS hoists variable and function declarations to the top of their scope. But —  and this is important  —  only the declarations , not the assignments. Why? Because JS reads it like: This is also why let and const behave differently — they’re hoisted too, but live in the “Temporal Dead Zone” until declared. 2. Closures Closures are like little memory vaults for your functions. They allow functions to remember variables from the scope they were created in, even after that scope has gone. Why care? T...