myHotTake

Tag: javascript to typescript

  • How to Gradually Integrate TypeScript into JavaScript Projects?

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


    Like many others, I have a book collection, with hundreds of books in different genres and editions. Each book represents a JavaScript file, filled with stories and information. I love my collection, but I start to notice that some of the books have pages that are out of order, or even worse, missing altogether. To bring some order to this chaotic collection, I decide to introduce a new system: TypeScript.

    TypeScript is like hiring a meticulous librarian who can gradually help me organize my collection. First, I don’t want to overwhelm my librarian by handing over all the books at once. Instead, I start with a single shelf. I select a manageable number of books that I think are the most important or the ones that need the most attention—these are my critical JavaScript files.

    With these selected books, the librarian starts by checking each page for consistency and completeness. She places labels on them, ensuring every chapter follows a certain structure and that all references are clear. This process is akin to adding TypeScript type definitions to my JavaScript files, ensuring that functions have defined input and output types.

    As the first shelf is beautifully organized, I gain confidence in my librarian’s abilities. I slowly begin to hand over more shelves, one by one, allowing her to apply the same meticulous care to the next batch of books. This gradual process is what I call “incremental adoption” of TypeScript. It allows me to maintain order while still enjoying my collection, without the overwhelming task of reorganizing everything at once.

    Eventually, my entire collection is neatly organized. Each book is easy to navigate, and any new additions follow the same structured system. In this way, my librarian—TypeScript—has not only brought order and clarity to my collection but also made future expansions smooth and error-free.

    Thanks for joining me on this journey! If you enjoyed the story, consider sharing it with fellow book lovers, or in this case, JavaScript developers.


    Step 1: Initialize TypeScript

    First, I need to introduce TypeScript into my project. I do this by running:

    npm install typescript --save-dev
    npx tsc --init

    This sets up a tsconfig.json file, which is like giving my librarian a set of rules and guidelines for organizing the books.

    Step 2: Convert a Few Files

    I start by converting a few of my JavaScript files to TypeScript. I choose files that are critical, much like my most valuable books. I rename them from .js to .ts. For instance, I take a simple file like calculate.js:

    function add(a, b) {
      return a + b;
    }

    And convert it to calculate.ts with type annotations:

    function add(a: number, b: number): number {
      return a + b;
    }

    This is similar to placing labels on my books, ensuring every function has clear input and output types.

    Step 3: Incremental Adoption

    I don’t want to convert everything at once, so I use the allowJs option in my tsconfig.json. This allows JavaScript files to coexist with TypeScript files, enabling me to slowly migrate more files over time:

    {
      "compilerOptions": {
        "allowJs": true,
        "checkJs": false, // If I want to avoid checking JS files initially
        "outDir": "./dist",
        "strict": true
      },
      "include": ["src/**/*"],
      "exclude": ["node_modules", "**/*.spec.ts"]
    }

    Step 4: Leveraging @ts-check

    For JavaScript files that I want to keep as JavaScript for now, I can still get TypeScript’s benefits by adding //@ts-check at the top of the file:

    // @ts-check
    function multiply(a, b) {
      return a * b;
    }

    This allows TypeScript to perform type-checking, acting as a safety net without fully converting the file.

    Key Takeaways

    • Incremental Adoption: Just like organizing a library one shelf at a time, I can adopt TypeScript gradually, starting with critical files.
    • Type Safety: Adding type annotations improves code readability and helps catch errors early.
    • Flexibility: Using allowJs and @ts-check provides flexibility, allowing JavaScript and TypeScript to coexist during the transition.
    • Scalability: Once fully adopted, TypeScript helps maintain a scalable and robust codebase.
  • How to Seamlessly Migrate Your JavaScript Code to TypeScript

    Hey there, if you enjoy this story, feel free to like or share it!


    My JavaScript codebase is an energetic pet shop. Each piece of code is like a different animal in the shop, full of life and purpose, but sometimes a little unpredictable. Now, I love my pet shop, but I want to bring a bit more order and predictability to it, so I decide to upgrade it using TypeScript, which is like hiring a team of expert animal trainers.

    First, I start by introducing these trainers to my shop—this is like setting up TypeScript in my project and configuring it. The trainers begin by observing the animals, understanding their quirks and behaviors, which is akin to gradually adding type annotations to my code. They don’t rush in to change everything at once; they take their time to learn and adjust.

    Next, the trainers begin training the animals one by one. They start with the more straightforward creatures, like the tame cats and dogs, which are like the simpler parts of my code. This corresponds to slowly converting JavaScript files to TypeScript, ensuring each piece functions as expected before moving on to the next.

    As the trainers work with the animals, they use specific techniques to handle each one, just like I use TypeScript’s powerful features such as interfaces and enums to make my code more robust and organized. This process helps in bringing clarity and structure, much like making sure each animal knows its space and role in the shop.

    Finally, after all the animals have been trained, my pet shop runs smoother than ever. The trainers have done their job, and the animals are happier and more predictable, just as my codebase is now more reliable and easier to maintain with TypeScript. With everything in order, I can introduce new animals or make changes with confidence, knowing that my trainers are there to keep things in check.

    So, transforming my JavaScript pet shop into a TypeScript haven made it a more harmonious and efficient place, just like how TypeScript can enhance a codebase. If you think this analogy helped, don’t hesitate to like or share!


    Step 1: Setting Up TypeScript

    Just like hiring the trainers, the first step is to set up TypeScript in my project. I start by installing TypeScript with:

    npm install --save-dev typescript

    Then, I create a tsconfig.json file to configure TypeScript options. This is like giving the trainers a guidebook on how to handle the animals:

    {
      "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "strict": true,
        "esModuleInterop": true
      },
      "include": ["src/**/*"]
    }

    Step 2: Gradual Introduction

    The trainers started with the more straightforward animals, so I begin by converting simple JavaScript files to TypeScript. For example, a basic JavaScript function for adding two numbers:

    // add.js
    function add(a, b) {
      return a + b;
    }

    In TypeScript, I can add type annotations to ensure the inputs are numbers:

    // add.ts
    function add(a: number, b: number): number {
      return a + b;
    }

    This change provides clarity and helps avoid errors, much like training the simple animals first.

    Step 3: Using TypeScript Features

    As the trainers used specific techniques, I utilize TypeScript’s features to enhance my code. Take an example of defining a shape:

    // shape.js
    function getArea(shape) {
      if (shape.kind === 'circle') {
        return Math.PI * shape.radius ** 2;
      }
      return shape.width * shape.height;
    }

    In TypeScript, I can define interfaces to describe the shape structure, making my code more robust:

    // shape.ts
    interface Circle {
      kind: 'circle';
      radius: number;
    }
    
    interface Rectangle {
      kind: 'rectangle';
      width: number;
      height: number;
    }
    
    type Shape = Circle | Rectangle;
    
    function getArea(shape: Shape): number {
      if (shape.kind === 'circle') {
        return Math.PI * shape.radius ** 2;
      }
      return shape.width * shape.height;
    }

    This helps ensure that my function handles each “animal” correctly, avoiding any surprises.

    Final Thoughts

    By gradually introducing TypeScript into my JavaScript codebase, I bring order and reliability to my project, just like the trainers did with the pet shop. TypeScript’s type system provides a safety net that catches errors early, making development smoother and more predictable.

    Key Takeaways:

    • Start with setting up TypeScript in your project with a tsconfig.json.
    • Gradually convert JavaScript files to TypeScript, beginning with simpler parts of your code.
    • Use TypeScript features like type annotations and interfaces to improve code robustness.
    • A step-by-step approach allows for a smooth transition, ensuring your project benefits from the added structure and safety of TypeScript.