Skip to Content
Course content

4: Compiling TypeScript to JavaScript

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was onboarding a junior developer named Leo. He had spent an entire afternoon writing a beautiful, type-safe module for a data dashboard. He felt great about it, linked the .ts file directly into the HTML <script> tag, and hit refresh. Naturally, the browser console exploded with syntax errors because the browser had no idea what a string[] or an interface was. Leo looked at me with total confusion, asking why the browser "didn't support TypeScript." It's a classic mistake, but it highlights the most fundamental truth about this language: TypeScript doesn't actually run anywhere.

TypeScript is a development-time tool. When your code is ready to actually hit a server or a browser, it has to be converted into plain old JavaScript. This process is called compilation (or more accurately, transpilation). The TypeScript Compiler, known as tsc, is the engine that does the heavy lifting. It checks your types, screams at you when you've made a mistake, and then strips all those type annotations away to leave behind clean JavaScript that any engine can execute.

The Magic of Type Erasure

The most important thing to understand about the compilation process is "type erasure." TypeScript doesn't add new runtime behavior to your code; it just validates the logic while you're writing it. Once tsc runs, every single interface, type alias, and type annotation vanishes.

Take this example of a simple function to handle a shopping cart item:

// Input: cart.ts
interface CartItem {
    id: number;
    price: number;
    quantity: number;
}

function calculateTotal(item: CartItem): number {
    return item.price * item.quantity;
}

const shirt: CartItem = { id: 1, price: 20, quantity: 2 };
console.log(calculateTotal(shirt));

If you run tsc cart.ts in your terminal, the compiler generates a cart.js file. If you open that file, you'll see the interface is completely gone and the type annotations on the function parameters and return types have been deleted:

// Output: cart.js
function calculateTotal(item) {
    return item.price * item.quantity;
}
var shirt = { id: 1, price: 20, quantity: 2 };
console.log(calculateTotal(shirt));


I've always found this liberating. It means you get the safety of a strict type system during development without paying a "performance tax" in the browser, because the final bundle is just standard JavaScript.

Orchestrating the Build with tsconfig.json

Running tsc filename.ts manually works for a single file, but in a real project, you'll have dozens of them. You don't want to list every file in your terminal command. This is where the tsconfig.json file comes in. It's essentially the "rulebook" for your project, telling the compiler exactly how to behave.

By running tsc --init, you create this configuration file. Two settings I always emphasize are target and outDir. The target setting allows you to decide which version of JavaScript to emit. If you're targeting ancient browsers, you might set this to ES5. If you're working in a modern Node.js environment, ES2020 or ESNext is usually the way to go. The outDir is equally critical—it keeps your project clean by sending all the generated .js files into a separate folder (usually called dist or build) so they don't clutter your source code.

When you have a tsconfig.json in your root directory, you can simply run tsc with no arguments. The compiler will scan your project, apply your rules, and compile everything in one go. It's a massive quality-of-life improvement that transforms TypeScript from a file-by-file tool into a professional build system.




📋 Practical Task

Exercise: Configuring a Production-Ready Build for a User-Auth Module

You have been handed a small module for handling user authentication, but it's currently just a set of loose TypeScript files. Your goal is to set up a formal compilation pipeline so the code can be deployed to a server.

Requirements:

  • Create a file named auth.ts with a function validateUser(user: {username: string, age: number}) that returns a boolean.
  • Initialize a TypeScript configuration file using the CLI.
  • Modify the tsconfig.json to meet these specific project requirements:
    • Set the target to ES6.
    • Set the outDir to a folder named dist.
    • Enable strict mode (ensure "strict": true is set).
  • Run the compiler using the shorthand command (without specifying the filename) and verify that the resulting .js file appears inside the dist folder.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.