TypeScript vs JavaScript is a debate that often arises among developers. While JavaScript has been the go-to language for web development for many years, TypeScript has gained significant popularity. Understanding the advantages of TypeScript over JavaScript can help make an informed decision when choosing a language for projects. So, let's dive into the world of TypeScript and explore why it has become a powerful contender in the realm of web development.

TypeScript (TS) offers several advantages over JavaScript (JS) that make it a popular choice for many developers:

  1. Static Typing: TypeScript introduces static typing to JavaScript, allowing you to specify the types of variables, function parameters, and return values. This helps catch type-related errors during development and provides better tooling support like autocompletion and type checking.
  2. Enhanced IDE Support: TypeScript is supported by many popular Integrated Development Environments (IDEs) like Visual Studio Code, which provides features like intelligent code completion, refactoring tools, and better code navigation. This improves developer productivity and code quality.
  3. Modern Language Features: TypeScript extends JavaScript with additional features such as classes, interfaces, modules, and more. These features enable you to write cleaner and more maintainable code, and also align with the latest ECMAScript (ES) standards.
  4. Stronger Tooling and Error Checking: TypeScript includes a type checker that analyzes your code for potential errors before runtime. This helps catch common mistakes and prevents unexpected behavior in your application, resulting in more reliable software.
  5. Better Code Maintainability: With static typing, interfaces, and clear type annotations, TypeScript code tends to be more self-documented and easier to understand. This improves code maintainability, readability, and reduces the likelihood of introducing bugs during development.
  6. Compatibility with JavaScript Ecosystem: TypeScript is a superset of JavaScript, which means that any valid JavaScript code is also valid TypeScript code. This allows you to leverage existing JavaScript libraries and frameworks seamlessly while gradually introducing TypeScript into your project.

Overall, TypeScript provides a stronger development experience, catches errors at compile-time, and improves code quality and maintainability. It is particularly beneficial for larger projects or teams, where the benefits of static typing and enhanced tooling support are more pronounced.

To bundle TypeScript with webpack, we’ll need to configure webpack to handle TypeScript files and transpile them into JavaScript. Here's a step-by-step guide on how to do it:

  1. Install the necessary dependencies:

    pnpm add -D ts-loader typescript
    
  2. Create a tsconfig.json file in the root of the project to configure TypeScript:

    {
      "compilerOptions": {
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "module": "es6",
        "skipLibCheck": true,
        "strict": true,
        "target": "es6"
      }
    }
    

    This basic tsconfig.json file includes the following compiler options:

    These options provide a configuration that enables strict type-checking, interoperability with different module systems, and compatibility with modern ECMAScript features.

  3. To enable TypeScript support in webpack, we'll use the ts-loader plugin. This plugin allows webpack to handle TypeScript files and perform necessary transpilation.

    const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    const MiniCssExtractPlugin = require('mini-css-extract-plugin')
    const { PurgeCSSPlugin } = require('purgecss-webpack-plugin')
    const TerserPlugin = require('terser-webpack-plugin')
    const path = require('path')
    
    module.exports = {
      entry: './src/index.ts',
      module: {
        rules: [
          {
            test: /\\.scss$/,
            use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
          },
          {
            test: /\\.ts$/,
            use: 'ts-loader',
          },
        ],
      },
      optimization: {
        minimizer: [new CssMinimizerPlugin(), new TerserPlugin()],
      },
      output: {
        filename: 'main.js',
        path: path.resolve(__dirname, '../dist'),
      },
      plugins: [
        new HtmlWebpackPlugin({
          filename: 'index.html',
          template: './src/index.html',
        }),
        new MiniCssExtractPlugin({
          filename: 'index.css',
        }),
        new PurgeCSSPlugin({
          paths: ['./src/index.html'],
        }),
      ],
    }
    
  4. Let's convert our src/index.js file to TypeScript (src/index.ts) to leverage the benefits of static typing and enhanced tooling provided by TypeScript.

    import './index.scss'
    
    const form = document.getElementById('add-form') as HTMLFormElement
    const output = document.getElementById('result') as HTMLOutputElement
    
    const foo = 'bar'
    
    function multiply(nums: number[]) {
      const result = nums.reduce((acc, num) => acc * num, 1)
      return result
    }
    
    function sum(nums: number[]) {
      const result = nums.reduce((acc, num) => acc + num, 0)
      return result
    }
    
    form.addEventListener('submit', (e) => {
      e.preventDefault()
      const first = +(e.target as HTMLFormElement)['first'].value
      const second = +(e.target as HTMLFormElement)['second'].value
      const result = sum([first, second])
      output.innerText = `Total = ${result}`
    })
    
  5. Run the webpack build command.

That's it! We have now set up webpack to bundle TypeScript files.

Resources

Documentation - What is a tsconfig.json

npm: ts-loader