myHotTake

Tag: TypeScript JavaScript integration

  • How Does TypeScript Ensure Type Safety in JavaScript?

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


    I’m a zookeeper managing a zoo filled with various animals, each with their own unique needs and behaviors. In my zoo, ensuring that each animal is placed in the right habitat is crucial for their well-being. TypeScript in my coding world acts like a diligent zoologist who helps me make sure that every animal is in the right enclosure and getting the right care.

    When I write code in TypeScript, it’s as if I’m planning to introduce a new animal into the zoo. Before the animal arrives, the zoologist reviews all the details about the animal’s needs—how much space it requires, what kind of food it eats, and the climate it thrives in. This is analogous to TypeScript checking the types in my code. If I try to put a penguin in the desert habitat meant for camels, the zoologist immediately alerts me to the mismatch. Similarly, TypeScript flags any type mismatches in the code, ensuring I don’t accidentally assign a string to a variable expected to be a number.

    Testing TypeScript code for type correctness is like having this meticulous zoologist constantly reviewing my plans. They ensure that the blueprint for each animal’s habitat matches the animal’s needs exactly, preventing any chaos. If there’s a mistake, like trying to feed leaves to a carnivore, the zoologist catches it before the animal even arrives. Likewise, TypeScript catches type errors during the development process, preventing runtime errors.

    By having this kind of check in place, I can confidently expand my zoo, knowing that each new addition will be comfortably and correctly placed. This proactive approach saves me from the chaos of relocating animals later, much like how TypeScript saves me from fixing type errors after my code is running.


    In my zoo, each habitat has specific signs and paths guiding visitors, analogous to the rules and structures TypeScript enforces in the code. When the tour begins, if everything is in the right place, visitors have a smooth experience—just like how properly typed code runs smoothly in JavaScript.

    Here’s a simple example of TypeScript enforcing type correctness:

    function feedAnimal(animalName: string, foodAmount: number): void {
      console.log(`${animalName} has been fed ${foodAmount} kilograms of food.`);
    }
    
    // Correct usage
    feedAnimal("Elephant", 50);
    
    // Type error example
    feedAnimal("Giraffe", "twenty"); // TypeScript will flag this as an error

    In this example, TypeScript ensures that when I call feedAnimal, the animalName is always a string and the foodAmount is a number. If I try to pass a string where a number should be, TypeScript catches this mistake before the code even runs.

    When it’s time to run the code in a JavaScript environment, TypeScript compiles down to JavaScript. Here’s how the compiled JavaScript might look:

    function feedAnimal(animalName, foodAmount) {
      console.log(animalName + " has been fed " + foodAmount + " kilograms of food.");
    }
    
    // JavaScript doesn't inherently check types, so this would not throw an error at runtime:
    feedAnimal("Giraffe", "twenty");

    In JavaScript, anything could happen if the types don’t match—just like if I didn’t have my zoologist helping me, I might accidentally create a chaotic zoo tour. TypeScript prevents these mistakes by enforcing rules before the tour even starts.

    Key Takeaways:

    1. TypeScript as a Planner: TypeScript acts like a meticulous planner, ensuring type correctness before the code runs, much like ensuring animals are in their correct habitats before the zoo opens.
    2. JavaScript as Execution: While TypeScript checks types at compile time, JavaScript executes the code at runtime. Without TypeScript, type mismatches might only be caught during execution, potentially causing issues.
    3. Error Prevention: By catching type errors early, TypeScript helps prevent runtime errors, leading to more robust and maintainable code.
    4. Smooth Experience: Just as a well-organized zoo offers a seamless experience for visitors, using TypeScript ensures smooth execution of JavaScript code by preventing type-related issues.
  • Why Use allowJs in TypeScript Projects? Here’s the Answer

    If you enjoy this story and find it helpful, feel free to give it a like or share it with someone who might benefit from it!


    I’m a school principal, and my school is renowned for its rigorous mathematics program. All students are expected to wear a uniform that symbolizes their dedication to math, representing the strict requirements we have—much like TypeScript with its type safety and structured approach. But one day, I decided to introduce a new program called “allowJs” where students who excel in arts, represented by JavaScript, could join the math club without having to wear the uniform.

    Initially, some teachers were skeptical. They were concerned that these artsy students, who dressed more casually and didn’t adhere to the strict dress code, might disrupt the disciplined environment. However, I believed there was value in their creativity and unique perspectives, and I wanted to integrate that into our math-focused culture.

    By allowing these art students to join, we started to see fascinating collaborations. The math students taught the art students about structure and equations, while the art students brought in creativity and new ways of thinking. This enriched our school’s culture, allowing us to tackle problems in innovative ways we hadn’t thought of before.

    The “allowJs” program wasn’t about changing our core identity but about embracing diversity and opening our doors to new ideas, much like how the allowJs option in tsconfig.json allows JavaScript files to coexist with TypeScript files in a project. It lets us leverage the flexibility and dynamism of JavaScript while still maintaining the strong foundation of TypeScript where needed.

    So, like my school’s decision to welcome the art students, enabling allowJs is about creating harmony between structure and creativity, allowing them to thrive side by side.


    I have a TypeScript project with a strict focus on types, just like my math students with their uniform. Here’s a basic TypeScript file:

    // math.ts
    function add(a: number, b: number): number {
        return a + b;
    }
    
    const result = add(5, 10);
    console.log(result); // Outputs: 15

    Now, let’s say I have a JavaScript file that brings in some creative flair, much like the art students:

    // creativity.js
    function multiply(a, b) {
        return a * b;
    }
    
    let product = multiply(5, 10);
    console.log(product); // Outputs: 50

    By setting "allowJs": true in my tsconfig.json, I allow these JavaScript files to join the TypeScript environment:

    {
      "compilerOptions": {
        "allowJs": true,
        "outDir": "./dist",
        "target": "es5"
      },
      "include": ["./**/*"]
    }

    With this configuration, my project can now seamlessly compile both math.ts and creativity.js, allowing the structured and creative elements to coexist:

    1. TypeScript Strength: Just like the disciplined math students, TypeScript provides type safety and structured code.
    2. JavaScript Flexibility: The spontaneous creativity of JavaScript allows for quicker experimentation and integration of existing scripts.

    Key Takeaways

    • Integration and Flexibility: The allowJs option lets JavaScript files coexist in a TypeScript project, similar to how the art students were integrated into the math-focused school. This allows for flexibility and the inclusion of existing JavaScript code.
    • Balanced Approach: Combining TypeScript’s type safety with JavaScript’s flexibility can lead to a more holistic and dynamic project, enriching the development process.
    • Gradual Transition: If you have an existing JavaScript codebase, allowJs provides a path for gradually transitioning to TypeScript without a complete rewrite.