myHotTake

Tag: TypeScript strict mode

  • Why Enable TypeScript’s Strict Mode? Benefits & Examples

    If you find this story helpful, feel free to like or share it!


    I’m running a bakery, and my bakery is like a TypeScript project. Every day, I’m juggling different ingredients: flour, sugar, eggs, and more. Now, in this bakery, I have a special assistant named Strict Mode. Enabling Strict Mode is like having a meticulous quality control inspector who ensures that every ingredient is measured precisely.

    One day, I decide to enable Strict Mode. Immediately, my inspector starts scrutinizing everything. “Is this flour fresh?” they ask, “Are these eggs cracked?” At first, it feels a bit overwhelming. I think about how, before the inspector, I could just toss in ingredients without much fuss. I didn’t have to worry too much about little details, and things generally turned out okay. But now, every step is under the microscope.

    This attention to detail means my baking process slows down initially. I have to double-check measurements and inspect the ingredients more closely. It’s a bit frustrating because it feels like I’m spending more time preparing than actually baking. However, as I get used to the inspector’s guidelines, I notice something interesting: my pastries are turning out consistently better. The cookies are perfectly chewy, the cakes rise just right, and the flavors are balanced.

    Enabling Strict Mode, like having this inspector, comes with trade-offs. It requires more time and attention upfront, but it also brings a higher level of confidence in the quality of my baked goods. I can serve my customers knowing that what they’re getting is made with precision and care. So, while it might take a bit longer, the end result is worth the extra effort. And in the world of TypeScript, just like in my bakery, precision and reliability are the secret ingredients to success.


    In JavaScript, without any type checking, you might write a function like this:

    function mixIngredients(ingredient1, ingredient2) {
        return ingredient1 + ingredient2;
    }
    
    const result = mixIngredients("flour", 2);
    console.log(result); // Outputs: "flour2"

    Here, I mixed a string with a number, and JavaScript didn’t complain. My pastries might end up tasting a bit strange, but I won’t realize the mistake until it’s too late.

    Now, let’s see how enabling TypeScript’s strict mode changes the game:

    function mixIngredients(ingredient1: string, ingredient2: number): string {
        return ingredient1 + ingredient2.toString();
    }
    
    const result = mixIngredients("flour", 2);
    console.log(result); // Outputs: "flour2"

    With strict mode, TypeScript will ensure that I specify the types of my ingredients. If I try to pass a number where a string is expected or vice versa, TypeScript will throw an error before I even run the code. This is like my inspector catching a cracked egg before it makes it into the batter. It prevents unexpected results, allowing me to fix the problem right away.

    Here’s another example showing how strictNullChecks—a part of strict mode—helps:

    function getIngredient(ingredient: string | null): string {
        if (ingredient === null) {
            throw new Error("Ingredient cannot be null");
        }
        return ingredient;
    }
    
    const ingredient = getIngredient(null); // TypeScript error: Argument of type 'null' is not assignable to parameter of type 'string'.

    By enforcing checks for null or undefined, strict mode ensures that I never accidentally try to bake without all my ingredients.

    Key Takeaways:

    1. Precision and Safety: Enabling strict mode in TypeScript is like having a meticulous inspector in a bakery. It ensures that all variables (ingredients) are used correctly, catching errors early on.
    2. Initial Overhead: There might be more setup and configuration upfront, similar to spending extra time measuring ingredients precisely. It can slow down initial development but leads to more reliable outcomes.
    3. Consistency: Just as a bakery benefits from consistent quality, a codebase benefits from the reliability that strict mode brings, reducing bugs and enhancing maintainability.
  • How Does TypeScript’s strict Flag Enhance JavaScript?

    If you enjoyed this story and found it helpful, feel free to like or share it with others who might appreciate a fresh perspective on TypeScript!


    I’m the captain of a ship called TypeScript, navigating the ocean of code. The ship is equipped with various tools and equipment, but there’s one particular feature that stands out: the strict flag. This flag is like my trusty compass, guiding us through treacherous waters and ensuring we stay on course.

    Before I raised the strict flag, the journey was a bit unpredictable. Sometimes, the seas were calm, but other times, I’d find myself in the middle of a storm, where unexpected bugs and errors would emerge from the depths, catching my crew off guard. It felt like navigating without a clear map, and the ship would occasionally drift off course, leading us into uncharted territories filled with danger.

    However, once I hoisted the strict flag, everything changed. This flag is like a compass that never fails. It ensures that my crew—comprising of various types and variables—are all in perfect harmony. With this compass, we avoid pitfalls such as loose type checks or unexpected null and undefined values that could cause havoc on our journey.

    The strict flag enforces discipline among the crew. It ensures that each crew member knows their role and sticks to it, preventing any mix-ups or confusion. For instance, if a task requires a specific skill set, the compass alerts me if someone unqualified tries to take it on, allowing me to correct course before any issues arise.

    With this level of precision and foresight, my ship sails smoothly, avoiding unexpected storms and ensuring a safe passage. The crew is confident, the journey is efficient, and we consistently reach our destination with fewer surprises along the way.

    So, the strict flag, much like my compass, transforms the journey from a risky adventure into a well-coordinated expedition. It keeps everything on track, ensuring that my ship, the TypeScript, sails confidently across the ocean of code.


    Here’s what our journey looks like without the strict flag:

    function greet(name) {
      return "Hello, " + name.toUpperCase();
    }
    
    let user = null;
    console.log(greet(user)); // This will throw an error at runtime!

    In this code, we’re trying to call toUpperCase on name, which could be null or undefined. Without the strict flag, TypeScript won’t alert us to this potential problem, much like sailing without a compass and hitting an unexpected storm.

    Now, let’s raise the strict flag and see how it changes our voyage:

    function greet(name: string | null) {
      if (name === null) {
        return "Hello, guest!";
      }
      return "Hello, " + name.toUpperCase();
    }
    
    let user: string | null = null;
    console.log(greet(user)); // Output: Hello, guest!

    With the strict flag enabled, TypeScript enforces stricter checks, ensuring we handle all possibilities, such as null values. This is akin to our compass pointing out potential pitfalls before we encounter them, allowing us to adjust our course proactively.

    Here’s another example illustrating type checks:

    Without strict mode:

    let age;
    age = "twenty";
    console.log(age + 1); // This will concatenate, not add!

    With strict mode:

    let age: number;
    age = 20;
    console.log(age + 1); // Output: 21

    The strict flag helps ensure that our variables are used correctly and consistently, much like crew members following precise instructions, leading to a smooth and predictable journey.

    Key Takeaways:

    • Early Error Detection: The strict flag helps identify potential issues at compile time, reducing runtime errors.
    • Improved Code Quality: By enforcing type checks and null safety, it ensures a more reliable and maintainable codebase.
    • Confidence in Development: With strict mode acting as a guiding compass, developers can navigate complex codebases with greater assurance.
  • 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.