Skip to content
LumenaryAcademy
Foundations 50 min

Why TypeScript

What a static type checker adds to JavaScript, how TypeScript came to be, and how to compile and run your first program.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Bugs you find before you run anything

Here is a JavaScript function with a typo in it:

javascript
function lineTotal(line) {
  return line.unitPrice * line.quantity;    // the field is really called unitPriceCents
}

JavaScript will not complain. Reading a missing property gives undefined, undefined * 2 is NaN, and the NaN flows quietly into a total, a database, an invoice. Someone notices days later, if at all. In a ten-line script you would spot the typo; in a code base of two hundred thousand lines written by forty people over five years, nobody can hold every object's shape in their head.

TypeScript is JavaScript with a type system on top. You describe the shapes of your data once, and the TypeScript compiler checks every line against those descriptions before the program runs. The typo above becomes a red underline in your editor, with the message Property 'unitPrice' does not exist on type 'OrderLine'. The same checker powers autocompletion, safe renaming across hundreds of files, and "go to definition", which is why many developers find TypeScript makes them faster, not slower.

This course assumes you know JavaScript, from the JavaScript course in this series or elsewhere. Everything you know still applies: TypeScript adds to the language, it doesn't replace it.

History & global context

Where TypeScript came from

By 2010 JavaScript was being used for applications far bigger than its designers had imagined, and teams at Microsoft building large web applications were feeling the pain. A team led by Anders Hejlsberg, who had earlier designed Turbo Pascal, Delphi and C#, set out to add optional static types to JavaScript without creating a new language that would split the ecosystem. Microsoft released TypeScript 0.8 as open source in October 2012, and version 1.0 in 2014.

Several early decisions explain why TypeScript succeeded where earlier attempts to type JavaScript did not:

  • A superset of JavaScript. Every JavaScript program is (nearly) a valid TypeScript program, so teams can adopt it one file at a time.
  • Types are erased. The compiler removes the annotations and emits ordinary JavaScript. Nothing about TypeScript exists at run time: no extra library, no slower code.
  • Follow the standard. New JavaScript features are supported as TC39 standardises them; TypeScript adds types, not its own runtime features (a few early exceptions, such as enum, predate this rule).
  • Structural typing. A value fits a type if it has the right shape, whatever it is called or wherever it came from, which matches how JavaScript code actually uses objects.
  • Useful rather than perfect. The design goals say plainly that a provably sound type system is not a goal; the team chose to balance correctness against productivity. You will meet the deliberate gaps, such as any and type assertions, and learn to keep them small.

Adoption grew when Google's Angular team wrote Angular 2 (released in 2016) in TypeScript, and when Microsoft's Visual Studio Code, itself written in TypeScript, made its editor features available to JavaScript and TypeScript developers alike. The community project DefinitelyTyped collected type descriptions for thousands of JavaScript libraries. Today TypeScript is the default for new professional JavaScript projects, and most popular libraries ship their own types.

The compiler has kept moving. TypeScript 6.0 (March 2026) made strict checking the default and retired many old options. In 2025 Hejlsberg announced a port of the compiler from TypeScript to Go, for builds around ten times faster; it shipped as TypeScript 7.0 in July 2026. The language itself is the same across these versions. This course's programs are checked with TypeScript 5.9, which is what its test suite has installed, with --strict turned on explicitly; where a default differs in newer versions, the lessons say so.

IntuitionH

What the compiler does

Definition— static type checking

A type describes a set of values and what you may do with them. Static type checking examines the program's text, without running it, and reports any operation that might be applied to the wrong kind of value. TypeScript's checker then erases the type annotations, producing the JavaScript that actually runs.

So the TypeScript compiler, tsc, does two separate jobs: it checks your code and reports errors, and it emits JavaScript. Here is a first program:

typescript
// hello.ts: a first TypeScript program
const learner: string = "Amara";
const firstRelease: number = 2012;

function welcome(name: string, year: number): string {
  return `Welcome, ${name}. In ${year}, TypeScript turns ${year - firstRelease}.`;
}

console.log(welcome(learner, 2026));

export {};
text
Welcome, Amara. In 2026, TypeScript turns 14.

The annotations are the parts after colons: learner: string says the constant holds a string, name: string, year: number give the parameters' types, and the : string after the parameter list is the return type. Compiled with tsc --target es2023 --module esnext hello.ts, the file hello.js that comes out is:

javascript
// hello.ts: a first TypeScript program
const learner = "Amara";
const firstRelease = 2012;
function welcome(name, year) {
    return `Welcome, ${name}. In ${year}, TypeScript turns ${year - firstRelease}.`;
}
console.log(welcome(learner, 2026));
export {};

The annotations are simply gone. That is type erasure, and it has a consequence you must never forget: types cannot do anything at run time. You cannot ask "is this value a Named?" while the program runs, because by then there is no Named.

The last line, export {}, exports nothing; it marks the file as a module. TypeScript treats a file with no import or export as an old-style global script, whose top-level names are shared with every other such file in the project and with the browser's global names. All the programs in this course are modules; real projects usually set the option "moduleDetection": "force" so that every file is a module without the extra line.

Types describe shapes

TypeScript's types are structural: a value matches a type if it has the required properties with the required types. Where it came from does not matter.

typescript
// Structural typing: a value fits a type if it has the right shape.
interface Named {
  name: string;
}

function greet(thing: Named): string {
  return `Hello, ${thing.name}!`;
}

class Robot {
  name: string;
  model: string;
  constructor(name: string, model: string) {
    this.name = name;
    this.model = model;
  }
}

const city = { name: "Kigali", population: 1_300_000 };

console.log(greet(city));                        // has a name: fits, extra fields and all
console.log(greet(new Robot("Tiko", "T-800")));  // a class instance with a name: fits too
console.log(greet({ name: "Ngozi" }));

// Types exist only at compile time. At run time there are just JavaScript values.
console.log(typeof city, Object.keys(city));

export {};
text
Hello, Kigali!
Hello, Tiko!
Hello, Ngozi!
object [ 'name', 'population' ]

An interface names an object shape (lesson three covers interfaces fully). city was never declared as Named, and Robot never mentions it, yet both fit, because each has a name that is a string. Languages such as Java and C# use nominal typing instead, where a class must declare which interfaces it implements. Structural typing suits JavaScript, where objects are often created on the fly as literals.

ComputationC

Installing and running TypeScript

TypeScript is an npm package. In a project folder (see the JavaScript course's last lesson for npm), install it as a development dependency, so every member of the team uses the same version:

bash
npm init -y
npm install --save-dev typescript
npx tsc --init          # creates a tsconfig.json with recommended settings
npx tsc                 # checks the project and writes .js files
node hello.js

tsconfig.json holds the compiler options for the whole project. The one tsc --init writes in TypeScript 5.9 is short and opinionated. Its main settings are:

json
{
  "compilerOptions": {
    "module": "nodenext",
    "target": "esnext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "verbatimModuleSyntax": true,
    "isolatedModules": true,
    "moduleDetection": "force",
    "skipLibCheck": true
  }
}

target is the JavaScript version to emit; module tells TypeScript how modules are written and resolved (here, the way Node does it). The rest are checks: strict turns on a family of essential checks, above all that null and undefined are not silently allowed everywhere, and you should never start a project without it. (It is on by default from TypeScript 6.0.) The other options tighten things further; lesson nine explains each one. For Node projects you also install Node's type descriptions with npm install --save-dev @types/node.

Other ways to run TypeScript

  • The Playground. typescriptlang.org/play runs the compiler in your browser: type on the left, see errors, the emitted JavaScript and the inferred type of anything you hover over. It is the best place to experiment with the examples in this course.
  • Node itself. Node can run a .ts file directly by stripping the types: since Node 22.18 just node hello.ts, and from Node 22.6 with the flag --experimental-strip-types. It does not type-check; it only removes annotations, so you still run tsc --noEmit (check without writing files) in your editor or build. It also cannot handle the few TypeScript features that generate code, such as enum; the compiler option erasableSyntaxOnly (TypeScript 5.8) flags them.
  • Tools. Bundlers such as Vite and runners such as tsx strip types too, very quickly, and leave checking to tsc. Deno and Bun run TypeScript natively.

The professional pattern is the same everywhere: a fast tool removes types so code runs immediately, and tsc --noEmit (in the editor, a pre-commit hook and continuous integration) does the checking.

Worked examplesH

Reading the compiler's errors

Here is a file with five mistakes, of kinds that are everyday bugs in JavaScript:

typescript
interface OrderLine {
  product: string;
  unitPriceCents: number;
  quantity: number;
}

function lineTotal(line: OrderLine): number {
  return line.unitPrice * line.quantity;
}

const basket: OrderLine[] = [
  { product: "rooibos tea", unitPriceCents: 450, quantity: 2 },
  { product: "honey", unitPriceCents: 1200 },
];

const expensive = basket.find((line) => line.unitPriceCents > 1000);
console.log(expensive.product.toUpperCase());
console.log(lineTotal(basket[0], 3));
const label: string = lineTotal(basket[0]);

Saved as main.ts and checked with tsc --strict, it gives:

text
main.ts(8,15): error TS2339: Property 'unitPrice' does not exist on type 'OrderLine'.
main.ts(13,3): error TS2741: Property 'quantity' is missing in type '{ product: string; unitPriceCents: number; }' but required in type 'OrderLine'.
main.ts(17,13): error TS18048: 'expensive' is possibly 'undefined'.
main.ts(18,34): error TS2554: Expected 1 arguments, but got 2.
main.ts(19,7): error TS2322: Type 'number' is not assignable to type 'string'.

Each line gives the file, the line and column, an error code (search for it when a message puzzles you) and a message. Taking them in turn: the misspelled property; an object that is missing a required field; a value that might be undefined (because find returns undefined when nothing matches) used as if it were certain; a call with the wrong number of arguments; and a number stored where a string was promised. The third deserves special attention: it is the TypeScript version of JavaScript's most common run-time error, "Cannot read properties of undefined", caught before the program runs. Here is the corrected program:

typescript
// The same kind of data, described once and checked everywhere it is used.
interface OrderLine {
  product: string;
  unitPriceCents: number;
  quantity: number;
}

function lineTotal(line: OrderLine): number {
  return line.unitPriceCents * line.quantity;
}

function orderTotal(lines: OrderLine[]): number {
  let total = 0;                                   // inferred: number
  for (const line of lines) total += lineTotal(line);
  return total;
}

const basket: OrderLine[] = [
  { product: "rooibos tea", unitPriceCents: 450, quantity: 2 },
  { product: "honey", unitPriceCents: 1200, quantity: 1 },
];

const cents = orderTotal(basket);
console.log(`Total: ${(cents / 100).toFixed(2)}`);

// Inference: TypeScript works out most types without annotations.
const names = basket.map((line) => line.product);  // string[]
const expensive = basket.find((line) => line.unitPriceCents > 1000);  // OrderLine | undefined
console.log(names.join(", "), "|", expensive?.product ?? "none");

export {};
text
Total: 21.00
rooibos tea, honey | honey

Notice how few annotations it needs. TypeScript infers types wherever it can: total is a number because it starts as 0, names is a string[] because map returns what its callback returns, and the parameter line inside each callback gets its type from the array. The usual style is to annotate function parameters and the shapes of your data, and let inference do the rest.

ExplanationH

Where types meet the outside world

Type erasure has one consequence that every TypeScript developer learns, usually the hard way. Inside your program, the checker makes sure values match their types. But values that come into the program, from a network response, a file, a form or localStorage, arrive at run time, after the checker has finished, and nothing has checked them:

typescript
interface User {
  name: string;
  age: number;
}
const user = JSON.parse('{"name":"Ama","age":"31"}') as User;
console.log(user.age + 1);
export {};
text
311

JSON.parse returns a value of type any, which means "don't check this", and as User is a type assertion: the programmer telling the compiler "trust me, this is a User". The compiler believes it, so user.age has type number in the source. But the JSON held the string "31", so at run time user.age + 1 concatenates and the program prints 311, the very kind of bug TypeScript is supposed to prevent.

The lesson is not that types are useless here, but that they are only as true as the place where data enters. Experienced teams treat every boundary as untrusted: they parse incoming data with a validation library (lesson nine uses one) or check it by hand, and only then give it a type. Everywhere inside that boundary, the types can then be trusted. Treat any and as as warning signs in code review: each one is a place where the checker has been told to look away.

Common misconceptionsH

Common misconceptions

Misconception

"TypeScript checks my data while the program runs." It checks your code, before it runs, and then disappears. Data from outside the program (a JSON response, a form, a file) is whatever it is at run time; if it doesn't match your types, TypeScript cannot know. Lesson nine shows how to validate such data at the boundary.

Misconception

"TypeScript code runs faster than JavaScript." It is JavaScript once compiled, so it runs at exactly the same speed. The benefits are fewer bugs, better tooling and code that is easier to change.

Misconception

"If it compiles, it works." The checker catches a large class of mistakes, but not wrong logic (a + that should be a -), and it can be deliberately bypassed with any and type assertions. Tests are still needed; types and tests catch different bugs.

Misconception

"TypeScript is a different language from JavaScript." It is JavaScript plus a type layer. The run-time behaviour, the standard library, the event loop and every quirk you learned in JavaScript are unchanged, which is why knowing JavaScript well remains essential.

Exercises

Exercises

Try these in the Playground or with tsc before you check the answers.

1. Why TypeScript

Warm-upHuman

You compile function double(n: number): number { return n * 2; } with tsc. What is in the emitted JavaScript?

Choose one

2. Why TypeScript

Warm-upComputational

What does this TypeScript program print?

const n: number = 5;
const s: string = "5";
console.log(n + Number(s), `${n}${s}`);
export {};

3. Why TypeScript

CoreComputational

This program compiles without errors. What does it print?

interface User {
  name: string;
  age: number;
}
const user = JSON.parse('{"name":"Ama","age":"31"}') as User;
console.log(user.age + 1);
export {};

4. Why TypeScript

CoreComputational

Given

interface Named { name: string }
function greet(thing: Named): string { return thing.name; }
const p = { name: "Ana", age: 3 };

which of these calls compile under tsc --strict? Choose all that apply.

Choose all that apply

5. Why TypeScript

CoreComputational

With const hit = basket.find((line) => line.quantity > 5);, why does tsc --strict reject hit.product?

Choose one

6. Why TypeScript

StretchHuman

A team runs TypeScript files with Node's built-in type stripping (node app.ts). What else should they run to get TypeScript's benefits?

Choose one

Further reading and resources