How TypeScript Becomes JavaScript

The compile step, demystified

7 min read

From .ts to .js

Browsers speak JavaScript, not TypeScript, so every TypeScript project has a translation step called compiling. The official tool is the TypeScript compiler, a command-line program called tsc. You point it at your .ts files and it produces plain .js files:

tsc greet.ts

What does the output look like? Mostly like your code with the types snipped out. This TypeScript:

function greet(name: string): string {
  return 'Hello, ' + name + '!';
}

const message: string = greet('Gwen');

compiles to this JavaScript:

function greet(name) {
  return 'Hello, ' + name + '!';
}

const message = greet('Gwen');

Look closely: the logic is identical. Only the annotations are gone. This is called type erasure, and it has a big consequence: types cost nothing at runtime. Your compiled website is not slower or larger because you used types. All the checking happened before the code ever shipped.

Checking happens even earlier than compiling

In practice you rarely wait for tsc to find your mistakes. Editors like VS Code run the TypeScript checker continuously as you type, drawing red squiggles under problems within seconds. The compile step then acts as a final gate: if there are type errors, the build fails, and broken code never reaches your users.

The settings file: tsconfig.json

Real projects keep compiler settings in a file called tsconfig.json at the project root. It answers questions like: which folder holds the source files, where should output go, and how strict should checking be. A minimal one looks like this:

{
  "compilerOptions": {
    "strict": true,
    "outDir": "dist"
  }
}

The one setting worth knowing today is "strict": true. It switches on TypeScript's most thorough checks, including the possibly-undefined checks you met in the optional properties lesson. New projects should always start strict; it is much easier than tightening things later.

Mental model: TypeScript is like a spell checker for code. It marks problems while you write, and the compile step is pressing print: the marks do their job and then disappear, leaving clean JavaScript on the page.

Quick check

Q1 What does the compiled JavaScript output of a TypeScript file look like?

Q2 What does "strict": true in tsconfig.json do?

Want to save your progress? It's free.

Create a free account