Photo by Kevin Ku on Unsplash

TypeScript: A Powerful Tool for JavaScript Development

Part 1: The benefits of TypeScript, its differences compared to JavaScript, integrating TypeScript with Webpack and more.

Irene Smolchenko
Bits and Pieces
Published in
11 min readMay 24, 2023

--

TypeScript has gained significant popularity among developers as a powerful superset of JavaScript. It introduces static typing, enhanced tooling, and improved scalability to JavaScript projects. In this article, we’ll cover the basics of TypeScript and important topics that will help you use TypeScript effectively in your projects. We’ll discuss the benefits of TypeScript, its differences compared to JavaScript, setting up the TypeScript compiler, configuring tsconfig, and integrating TypeScript with Webpack. Let’s get started and explore the world of TypeScript!

What is TypeScript?

TypeScript is a strong, open-source programming language developed by Microsoft. It is built on top of JavaScript, offering additional features and static typing.

Static Typing: TypeScript introduces static typing, allowing us to explicitly define the types of variables, function parameters, and return values. This provides type safety and helps catch errors at compile-time, during development, leading to improved code quality and fewer runtime issues. This early error detection significantly reduces debugging time and enhances overall developer productivity. Example:

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

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

Enhanced Tooling: TypeScript offers superior tooling support, including features like intelligent code completion, automatic refactoring, and better code navigation. These tools enhance our productivity as developers and make it easier to explore and work with our code effectively.

  • Intelligent code completion - a feature provided by code editors or integrated development environments (IDEs) that understand the TypeScript language and its types. It suggests relevant code completions based on the context, available methods, properties, and types.
    In the below example, as you type person., the code editor provides a list of available properties (name and age) of the person object. This helps in writing code faster and reduces the chances of typos or accessing non-existent properties.
// TypeScript code completion
interface Person {
name: string;
age: number;
}

const person: Person = {
name: "John",
age: 30,
};

console.log(person.); // Code editor suggests available properties like 'name' and 'age'
  • Automatic refactoring - refers to the ability of code editors or IDEs to perform automated code transformations without manually modifying each occurrence. This helps in maintaining consistency and efficiency when making changes to code.
    In the below example, when you perform an automatic refactoring to rename the parameter from name to fullName, the code editor updates all occurrences of the parameter throughout the codebase. This ensures consistency and saves time when making changes across large codebases.
// TypeScript automatic refactoring
function greet(name: string) {
return `Hello, ${name}!`;
}

greet("John"); // Original implementation

// Automatic refactoring: Rename the parameter 'name' to 'fullName'
function greet(fullName: string) {
return `Hello, ${fullName}!`;
}

greet("John"); // Updated implementation
  • Better code navigation — allows developers to quickly jump to the definition of a symbol, find references, and navigate through the codebase. This helps in understanding and exploring code more efficiently.
    In the below example, if you want to understand how the getPersonName function retrieves the person's name, you can navigate to its definition or the definition of the person object. This improves code comprehension and enables efficient exploration of the codebase.
// TypeScript code navigation
interface Person {
name: string;
age: number;
}

function getPersonName(person: Person) {
return person.name;
}

const person: Person = {
name: "John",
age: 30,
};

console.log(getPersonName(person)); // Navigate to the definition of 'getPersonName' or 'person.name'

Improved Scalability: TypeScript enables developers to write self-documenting code with explicit type annotations. This makes the codebase more understandable and maintainable, especially as the project size increases. The ability to define interfaces, classes, and modules that possess well-defined agreements aids in organizing the codebase and promoting collaborative efforts among developers. Examples:

// JavaScript - math.js
export function add(a, b) {
return a + b;
}

// TypeScript modules - math.ts
// Define explicit types for exported members and ensure type safety when importing and using those members in other modules
export function add(a: number, b: number): number {
return a + b;
}

// app.ts
import { add } from "./math";
console.log(add(2, 3)); // Output: 5
// JavaScript
function greet(person) {
console.log(`Hello, ${person.name}!`);
}

const john = {
name: "John Doe",
age: 30,
email: "john@example.com",
};

greet(john);



// TypeScript
// interfaces allow you to define custom types and enforce their structure.
interface Person {
name: string;
age: number;
email: string;
}

// ensures that the argument passed to the function is of type Person as expected,
function greet(person: Person) {
console.log(`Hello, ${person.name}!`);
}

const john: Person = {
name: "John Doe",
age: 30,
email: "john@example.com",
};

greet(john);

💡 Along with TypeScript you could also use an open-source toolchain like Bit. With Bit you can easily share, discover, and reuse individual components across different projects, which can significantly reduce code duplication and improve code quality. Bit integrates seamlessly with TypeScript, making it easy to share and manage typed components.

Learn more:

Setting up TypeScript compiler

The TypeScript compiler is a tool that converts TypeScript code into JavaScript code, allowing it to run in any JavaScript runtime environment.
To install the TypeScript compiler, you can follow these steps:

  1. Install Node.js: Ensure that you have Node.js installed on your machine. You can download the latest version of Node.js from the official website and follow the installation instructions specific to your operating system.
  2. Verify Node.js and NPM/Yarn installation: Open your terminal or command prompt and run the following commands to check if Node.js and NPM/Yarn are properly installed:
    node -v
    npm -v
    If you see the version numbers for both Node.js and NPM/Yarn, it means they are installed correctly.
  3. Install TypeScript: To install TypeScript, you have two options: global installation or local installation within your project. Follow these steps in your terminal or command prompt:
    For local installation in your project, run the following command:
    npm install typescript
    For global installation on your machine, run either of the following commands:
    npm install -g typescript
    OR
    yarn global add typescript
    This command will download and install the TypeScript compiler globally, making it accessible from any directory.

    NOTE: TypeScript versions can bring significant changes, even in minor revisions. Upgrading to a new version may result in transpilation issues. To address this, it’s recommended to install TypeScript directly in your project and utilize npx to execute it when necessary, instead of depending on a globally installed TypeScript.
  4. Verify TypeScript installation: Run the following command to verify that TypeScript is installed correctly:
    tsc -v
    This should display the TypeScript compiler version, indicating that the installation was successful.

With the TypeScript compiler installed, you are now ready to transpile TypeScript code into JavaScript. You can create a TypeScript file (e.g., app.ts) and compile it using the tsc command:
tsc app.ts
This command will generate a JavaScript file (app.js) that can be executed in any modern browser or Node.js environment.

Configuring tsconfig

The tsconfig.json file is a configuration file used by the TypeScript compiler (tsc) to specify compiler options and project settings for a TypeScript project. It allows developers to customize the behavior of the TypeScript compiler and tailor it to their project's requirements.
To understand and utilize the TypeScript Compiler effectively, let’s break down the steps and commands involved:

  1. Initialize a TypeScript project: Create a new directory for your TypeScript project and navigate to it in your terminal or command prompt.
  2. Initialize the project with TypeScript: Run the following command to initialize a TypeScript project in the current directory:
    tsc --init
    This command generates a tsconfig.json file, which serves as the configuration file for the TypeScript compiler.
  3. Configure tsconfig.json: Open the tsconfig.json file in a text editor and customize it according to your project requirements. This file allows you to specify compiler options and manage TypeScript project settings.
    Below is an example configuration to enable strict type checking and emit JavaScript files in a specific directory. You can also explore various compiler options in the official TypeScript documentation.
{
"compilerOptions": {
"strict": true,
"outDir": "dist"
}
}

4. Compile TypeScript code: Place your TypeScript files (e.g., app.ts) in the project directory. To compile TypeScript code into JavaScript, run the following command:
tsc
This command instructs the TypeScript compiler (tsc) to compile all TypeScript files in the current directory based on the configuration specified in tsconfig.json. The compiled JavaScript files will be emitted in the specified output directory (dist in the example configuration).

5. Use the compiled JavaScript files: Once the TypeScript code is successfully compiled, you can use the generated JavaScript files (app.js in this case) in your project. For example, if you're working with a web application, you can include the compiled JavaScript files in your HTML file using the <script> tag:

<!-- index.html -->
<html>
<head>
<title>My TypeScript App</title>
</head>
<body>
<!-- Include the compiled JavaScript file -->
<script src="app.js"></script>
</body>
</html>

By understanding the TypeScript Compiler (tsc) and customizing the tsconfig.json file, you can tailor the compilation process to suit your project's needs. This allows for efficient management of TypeScript projects and enables you to leverage the full potential of TypeScript's features and capabilities.

Integrating TypeScript with Webpack

Webpack is a module bundler, a tool that takes different parts of a web application, like JavaScript files and stylesheets, and combines them into a single file. This makes the application load faster and perform better.
Setting up Webpack for TypeScript offers several advantages for web development projects.

  • Module Bundling: TypeScript allows developers to organize their code into modules. Webpack complements this by bundling these modules together, including any dependencies, into a single output file. This reduces the number of network requests needed to load the application, improving the loading speed and performance of your web application.
  • Code Optimization and Minification: Webpack offers various optimizations for your application’s code, including code optimization, dead code removal, and minification. These optimizations are achieved through the use of plugins and loaders, both configured in the Webpack configuration file (webpack.config.js). While loaders are responsible for transforming and processing individual files (such as CSS, images, and fonts), plugins offer a broader range of functionalities and optimizations for the entire build process.
    By applying these optimizations, the bundle size is reduced, resulting in improved overall performance of your application.
  • Code Transpilation: TypeScript is a superset of JavaScript that includes additional features not supported by all browsers. Webpack, in combination with a TypeScript loader, can transpile TypeScript code into JavaScript that is compatible with a wide range of browsers. This ensures that your application can run on different environments without compatibility issues.
  • Development Server and Hot Module Replacement: Webpack includes a built-in development server that allows you to test and view your TypeScript application locally during development. Additionally, it supports Hot Module Replacement (HMR), which enables you to see instant changes in your application without the need for a full page reload. This makes the development process more efficient and helps maintain a smooth development workflow.

Now that we understand the benefits of using Webpack for TypeScript development, let’s dive into the process of setting it up.
To set up Webpack for TypeScript, follow these steps:

  1. Initialize a new project: Create a new directory for your project and navigate to it in your terminal or command prompt.
  2. Initialize the project and install dependencies: Run the following command to initialize a new project and generate a package.json file:
    npm init -y
    This command initializes a new Node.js project with default settings. Next, install the necessary dependencies:
    npm install webpack webpack-cli typescript ts-loader -- save-dev
    This installs Webpack, the Webpack CLI, TypeScript, and the TypeScript loader for Webpack as development dependencies.
  3. Create a Webpack configuration file: Create a new file named webpack.config.js in the project directory. Open the file in a text editor and add the below configuration. This configuration specifies the entry point (index.ts), output directory (dist), output filename (bundle.js), resolves TypeScript and JavaScript files, and uses the ts-loader to transpile TypeScript files.
const path = require("path");

module.exports = {
entry: "./src/index.ts",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
},
resolve: {
extensions: [".ts", ".js"],
},
module: {
rules: [
{
test: /\.ts$/,
use: "ts-loader",
exclude: /node_modules/,
},
],
},
};

4. Create a TypeScript file: In the project directory, create a src folder if it doesn't exist. Inside the src folder, create a TypeScript file (e.g., index.ts) with some sample code.

// index.ts
const greeting: string = "Hello, TypeScript!";
console.log(greeting);

5. Build the project: In your terminal or command prompt, run the following command to build the project using Webpack.
npx webpack --config webpack.config.js
This command executes Webpack with the specified configuration file and generates a bundled JavaScript file (bundle.js) in the dist directory.

6. Use the bundled file: You can now include the bundled JavaScript file (bundle.js) in your HTML file or use it in your project as needed. By including the bundled JavaScript file in your HTML, you can open your HTML file in a web browser, and the JavaScript code will be executed.

By following these steps, you have successfully set up Webpack for TypeScript. Webpack will handle the transpilation of TypeScript files, bundle them together, and optimize the output for production. You can further customize the Webpack configuration to leverage additional features using the official documentation.

Conclusion

TypeScript’s static typing, advanced features, and seamless integration with JavaScript make it a powerful tool for modern web development. With the TypeScript compiler, you can ensure cross-platform compatibility and easy deployment by transpiling TypeScript code into JavaScript. By configuring the tsconfig file, you can customize compiler options for strict type checking, better code organization, and an enhanced development experience. Integrating TypeScript with Webpack brings the benefits of seamless module bundling, optimizing your application’s performance and reducing network requests.

In the upcoming articles, we will explore more about TypeScript’s powerful features. We’ll cover topics like type annotations, interfaces, classes, generics, and advanced concepts in TypeScript. By learning and using these features, you can greatly enhance your productivity and create more reliable code for your projects. So, stay tuned!

By buying me a virtual croissant on Buy Me a Coffee, you can directly support my creative journey. Your contribution helps me continue creating high-quality content. Thank you for your support!

Build Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

--

--

🍴🛌🏻 👩🏻‍💻 🔁 Front End Web Developer | Troubleshooter | In-depth Tech Writer | 🦉📚 Duolingo Streak Master | ⚛️ React | 🗣️🤝 Interviews Prep