myHotTake

How to Safely Enable TypeScript ‘Strict’ in Legacy Code

If you enjoy this story, feel free to like or share it with others!


I’m an architect tasked with updating an old, mansion. This mansion represents a legacy codebase in TypeScript. Over the years, many builders have come and gone, each with their own way of doing things. Some rooms are beautifully designed, while others are a tangled mess of wires and beams. My goal is to bring harmony and safety to this mansion without tearing it down completely.

In my toolkit, I have a very special blueprint—it’s called the strict flag. This blueprint acts like a meticulous safety inspector, ensuring every nook and cranny of the mansion adheres to modern building codes. But here’s the thing: I can’t just drop it into the mansion all at once, or the entire structure might crumble under the weight of its demands.

I start by examining the mansion room by room. First, I enable the strict blueprint in a small, manageable area—a guest room that’s rarely used. I tweak the wiring, reinforce the beams, and make sure the plumbing is spotless, all according to the blueprint. With each improvement, the room becomes more robust, and I gain confidence in the process.

Gradually, I expand my reach, room by room, floor by floor. In some areas, I find ancient relics—old furniture that’s been patched up over and over. Here, the strict blueprint helps me decide whether to restore them or replace them entirely. I take my time, ensuring that each change doesn’t disrupt the overall balance of the mansion.

As I work, I occasionally come across hidden passageways and secret compartments. These represent the complex parts of the codebase that resist the constraints of the strict blueprint. I approach these with care, understanding that some secrets must be preserved for the mansion to retain its charm.

Over time, the mansion transforms. It becomes a place where history and modernity coexist in harmony. Rooms that once seemed haphazard are now cohesive and secure. The mansion stands as a testament to careful planning and gradual refinement, all guided by the wise counsel of the strict blueprint.

And just like that mansion, the legacy codebase evolves, becoming more reliable and easier to maintain, without losing the essence of what made it unique in the first place.


Entering the First Room

In the first room, I found some old JavaScript code. It was like a cozy but cluttered study, filled with books stacked haphazardly. A simple variable declaration caught my eye:

let bookTitle = "The Great Gatsby";
bookTitle = 42; // Uh-oh, this shouldn't happen!

To bring order, I introduced TypeScript and enabled the strict flag in a tsconfig.json file:

{
  "compilerOptions": {
    "strict": true
  }
}

With strict mode on, TypeScript immediately flagged the error. I adjusted the code, giving it a clear type:

let bookTitle: string = "The Great Gatsby";
// bookTitle = 42; // Error: Type 'number' is not assignable to type 'string'

Exploring More Rooms

As I moved to another room, I found a piece of JavaScript code that was handling a potentially undefined value, much like a dusty, unused attic:

function getBook(isbn) {
  if (isbn === "123") {
    return { title: "The Great Gatsby" };
  }
  return undefined;
}

const book = getBook("123");
console.log(book.title); // What if book is undefined?

The strict flag helped me unveil potential issues with strictNullChecks. I refined the function:

function getBook(isbn: string): { title: string } | undefined {
  if (isbn === "123") {
    return { title: "The Great Gatsby" };
  }
  return undefined;
}

const book = getBook("123");
if (book) {
  console.log(book.title); // Safe access
}

Final Thoughts

As I continued to apply the strict flag throughout the mansion, each room became safer and more reliable. The TypeScript compiler, with its strict checks, was like a vigilant guardian ensuring that everything was in its rightful place.

Key Takeaways:

  • Incremental Adoption: Just like renovating a mansion room by room, gradually enabling strict mode in a legacy codebase allows for manageable improvements.
  • Type Safety: The strict flag helps catch potential errors early, such as type mismatches and null or undefined references.
  • Enhanced Maintainability: By enforcing strict type checks, the codebase becomes more robust, making future maintenance easier.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *