Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 96 ยท Getting Started

How TypeScript Works

See what the TypeScript compiler does - type-checking, emitting JavaScript and erasing types - and how tsc, Node type stripping and bundlers like Vite fit in.

Browsers and Node.js run JavaScript, not TypeScript. So somewhere between the code you write and the code that runs, a tool has to turn TypeScript into JavaScript. Understanding that step explains almost every "why does TypeScript behave like this?" question you'll have later: why types can't check data from a server, why some syntax is fine in one tool and rejected by another, and why a project can build successfully while still having type errors.

In this lesson you'll learn the two separate jobs of the TypeScript compiler, see type erasure in action, compare the tools that run TypeScript today (tsc, Node.js's built-in type stripping and bundlers such as Vite), and set up a project with tsc --init.

The compiler's two jobs

The TypeScript compiler, tsc, does two independent things:

  1. Type-checking. It reads all your files, works out the type of every expression and reports anything that doesn't fit, such as a string passed where a number is required.
  2. Emitting. It writes JavaScript files: your code with the type syntax removed, and optionally converted to an older JavaScript version.

The key word is independent. By default, tsc emits JavaScript even when there are type errors, because the emitted code doesn't depend on the types at all. Projects that want "no errors, no output" turn on the noEmitOnError option. Our editors work that way, which is why a type error stops your example from running.

Here's what emitting looks like. This TypeScript:

TypeScript
interface Product {
  name: string;
  price: number;
}

function formatPrice(product: Product, currency: string = 'USD'): string {
  return `${product.name}: ${product.price.toFixed(2)} ${currency}`;
}

const lamp: Product = { name: 'Desk lamp', price: 24.5 };
console.log(formatPrice(lamp));

becomes this JavaScript:

JavaScript
function formatPrice(product, currency = 'USD') {
  return `${product.name}: ${product.price.toFixed(2)} ${currency}`;
}

const lamp = { name: 'Desk lamp', price: 24.5 };
console.log(formatPrice(lamp));

The interface disappeared completely, and so did every : Product, : string and : number. Everything else is untouched. Run the TypeScript version yourself:

TypeScript Types in, plain JavaScript out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints Desk lamp: 24.50 USD and Desk lamp: 24.50 EUR. The code that actually ran is the JavaScript above.

Type erasure: types vanish at runtime

Removing the types is called type erasure. It's a deliberate design choice: TypeScript adds no runtime cost and no runtime library, and the output is the JavaScript a careful developer would write by hand.

The consequence is simple but important: you can't ask about a TypeScript type while the program runs. An interface is not a value. There's nothing to inspect, loop over or compare against.

TypeScript An interface is not a runtime value (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler stops you with main.ts(8,18): error TS2693: 'Point' only refers to a type, but is being used as a value here. Because Point won't exist after erasure, instanceof Point could never work. To check data at runtime you write real JavaScript checks, such as typeof value === 'number', which you'll practice in Narrowing and Custom Type Guards.

Types are promises, not checks

Erasure also means a type annotation never converts or validates anything. It's a promise you make to the compiler. If the promise is false, the compiler believes you anyway, and the program carries on with the wrong value.

The classic case is data that comes from outside the program. JSON.parse can return anything, so TypeScript lets you decide what it is:

TypeScript An annotation does not validate data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program type-checks, yet it prints string and 111. TypeScript believed the annotation, but the JSON contained the string "11", and "11" + 1 is string concatenation. Nothing at runtime ever looked at the Settings interface, because it no longer exists.

Check data at the boundaries. Anything that enters your program while it runs (JSON, form input, files, environment variables, API responses) has no trustworthy type until real code has checked it. Typing APIs and JSON Data shows how to do that properly. JSON.parse returns the unsafe type any, which is why the annotation above was accepted; any, unknown, never and void explains why unknown is the safer choice.

A few features do produce code

Almost all TypeScript syntax is "erasable": delete it and you have valid JavaScript. A handful of older TypeScript features are different, because they create real runtime values. The best-known one is enum:

TypeScript An enum exists at runtime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints { '0': 'Up', '1': 'Down', Up: 0, Down: 1 }, then 1, then Up. The compiler had to generate an object for Direction, so it can't simply delete the enum. The same goes for namespace blocks that contain values and for constructor parameter properties in classes. These features are fully supported, and you'll learn them in Enums and Namespaces. But they matter for the next section, because some tools only know how to delete types.

Changing the JavaScript version

The second part of emitting is optional: tsc can rewrite modern syntax for older engines. The target option chooses the JavaScript version of the output, such as es2020 or es2024. If your code uses a newer feature than the target supports, the compiler rewrites it, as long as a rewrite exists.

For example, with an old target, a class field written in TypeScript can be turned into an assignment inside the constructor. With a modern target, it's left alone. Today almost every project targets a recent version, because all current browsers and Node.js releases understand modern JavaScript. Our editors use es2024.

Rewriting syntax is not the same as adding missing functions. If you call Object.groupBy and the engine doesn't have it, tsc won't add it for you. That's the job of the lib option (which tells the type-checker what exists) and of polyfills. The tsconfig.json File covers both.

The tools that run TypeScript

There are three common ways to turn TypeScript into running JavaScript, and real projects often combine them.

tsc: the official compiler

tsc is the only tool that type-checks. It can also emit JavaScript. Typical uses:

Terminal
npx tsc            # check and emit using tsconfig.json
npx tsc --noEmit   # only type-check, write nothing
npx tsc --watch    # re-check whenever a file changes

tsc --noEmit is extremely common: another tool produces the JavaScript, and tsc is used purely as a checker, for example in a pre-commit hook or a CI pipeline.

Node.js type stripping

Recent versions of Node.js can run .ts files directly. Since Node.js 22.18 and in Node.js 24, type stripping is on by default:

Terminal
node app.ts

Node.js does not type-check. It replaces the type syntax with whitespace and runs the result, so line and column numbers stay the same. Because it only deletes, it rejects features that need generated code, such as enum and parameter properties (unless you opt into an extra flag). It also expects import type for type-only imports and real file extensions like ./util.ts in import paths. You'll find the details in TypeScript with Node.js.

TypeScript 5.8 added the erasableSyntaxOnly option, which makes tsc report any syntax that can't simply be deleted. Projects that run their code with Node.js type stripping turn it on so the checker and the runtime agree.

Bundlers and fast transpilers

Front-end tools such as Vite, esbuild, swc and the build systems inside frameworks convert TypeScript to JavaScript too. They work one file at a time and only remove types, which is why they're so fast. Like Node.js, they don't type-check. A Vite dev server will happily serve a file full of type errors.

That leads to the most common setup in real projects:

Job Tool
Turn .ts into running code, fast Vite, esbuild, swc, Node.js type stripping
Find type errors tsc --noEmit (and your editor, continuously)

Because these tools compile each file on its own, they can't handle features that need information from other files. The isolatedModules and verbatimModuleSyntax options make tsc warn about such code, so it stays safe for single-file tools.

A green dev server is not a passing type-check. If your project uses Vite or Node.js type stripping, add tsc --noEmit to your npm test or CI step. Otherwise type errors can slip into production unnoticed.

TypeScript 7: the native compiler

For most of its history, tsc was itself written in TypeScript and ran on Node.js. TypeScript 7 replaced it with a native port written in Go. The behavior and the error messages are designed to match TypeScript 6.0, but type-checking a large project is typically around ten times faster, and editors respond more quickly too, thanks to native code and parallel checking across CPU cores. During its preview the native compiler shipped as a separate tsgo command; in TypeScript 7 it is simply tsc.

TypeScript 6.0 was the last version of the old JavaScript-based compiler. It deprecated a set of outdated options (such as target: es5, moduleResolution: node10, outFile and baseUrl), and TypeScript 7 removed them. If you start a new project today, none of that affects you.

Installing TypeScript and starting a project

You don't need to install anything for this course, because the editors run TypeScript on our server. When you're ready to work locally, you need Node.js and a project folder:

Terminal
mkdir my-app
cd my-app
npm init -y
npm install --save-dev typescript @types/node
npx tsc --version

Install TypeScript per project as a dev dependency instead of globally. That way every developer and the CI server use the same compiler version, pinned in package.json. @types/node adds type information for Node.js APIs such as node:fs and process.

Next, create a configuration file:

Terminal
npx tsc --init

This writes a tsconfig.json with a modern set of options and comments explaining them. Since TypeScript 6.0, strict is on by default and types starts empty, so you list the global type packages you want (for example "types": ["node"]). You'll go through the important settings in The tsconfig.json File.

Write a file, check it, emit it and run it:

TypeScript
// src/main.ts
const greeting: string = 'Hello from TypeScript';
console.log(greeting);
Terminal
npx tsc                 # writes JavaScript (to outDir if it is set)
node dist/main.js       # runs the emitted file (if outDir is "dist")
node src/main.ts        # or let Node.js strip the types itself

Putting it together

One more runnable example. It works with types the compiler knows about while keeping in mind that only values exist at runtime. The runtime check with typeof is real JavaScript, so it survives erasure:

TypeScript Compile-time types plus a runtime check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first call prints { id: 7, quantity: 2 }. The second throws Error: Not a valid order: { "id": 8, "quantity": "two" }, because this time real code checked the data instead of trusting an annotation. Don't worry about every detail of the if yet; Narrowing explains how TypeScript follows checks like these.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. By default, what does tsc do with a file that has type errors?

    Type-checking and emitting are independent. tsc emits even with errors unless you turn on noEmitOnError, which our editors use.
  2. 2. Why does if (value instanceof Point) fail to compile when Point is an interface?

    Interfaces exist only for the type-checker. After erasure nothing named Point remains, so TypeScript reports TS2693: 'Point' only refers to a type.
  3. 3. const s: Settings = JSON.parse('{"volume": "11"}') type-checks. What is typeof s.volume at runtime if Settings says volume: number?

    Annotations never convert or validate values. The JSON contains a string, so the property is a string at runtime.
  4. 4. Which of these tools type-checks your code?

    Bundlers, fast transpilers and Node.js only remove types. tsc (or tsc --noEmit) is the tool that actually checks them.
  5. 5. Why can't Node.js type stripping run a file that declares an enum (without extra flags)?

    Type stripping only replaces type syntax with whitespace. An enum needs generated JavaScript, so it is not erasable syntax.

Summary

  • tsc has two independent jobs: type-check the program and emit JavaScript. It emits even with errors unless noEmitOnError is set.
  • Type erasure removes all type syntax. Types cost nothing at runtime, but you can't inspect them or rely on them to validate outside data.
  • A few features, like enum, produce real JavaScript and aren't erasable. erasableSyntaxOnly reports them.
  • target controls the JavaScript version of the output; lib tells the checker which built-in APIs exist.
  • Node.js (22.18+, 24) runs .ts files by stripping types; Vite, esbuild and swc also strip types. None of them type-check, so run tsc --noEmit too.
  • TypeScript 7 is a native Go port of the compiler: same language, roughly ten times faster.
  • Install TypeScript per project with npm install --save-dev typescript, then run npx tsc --init.

Next: Your First Types โ€” annotating variables and functions, and reading type errors like a pro.