Introduction to TypeScript: The Safety Inspector

Introduction to TypeScript: The Safety Inspector in TypeScript: Before a trench is dug on a construction site, a set of drawings goes to the building control…

The Analogy: The Plan Check at the Building Control Office

Before a trench is dug on a construction site, a set of drawings goes to the building control office. A checker sits down with them, a scale rule, and a folder of standing rules, and works through the sheets line by line. Is the stair rise inside the permitted range. Is that lintel rated for the span it bridges. Does the escape corridor stay wide enough once the door swings into it. The checker never visits the site, never touches a brick, and produces nothing but marks on paper: approvals, queries, refusals.

What comes back is the same set of drawings, stamped. The stamp does not change the building. The crew still pours the same concrete in the same place, and if you walked through the finished building you would find no trace of the checker anywhere in it: no inspector living behind the plasterboard, no extra weight on the doors, no line on the electricity bill. The whole apparatus exists in the gap between the moment a drawing is finished and the moment work starts, and then it is gone.

The reason anyone tolerates the delay is arithmetic. A wrong lintel found on paper costs a re-draw and an afternoon. The same wrong lintel found after the wall is up costs the wall. Found after the building is occupied, it costs very much more than the wall, and the cost is no longer only money. The checker is not there to be clever. The checker is there to move the discovery of a mistake as early as it will go, because that is the only variable anybody controls.

The failure mode deserves precision, because it is exactly the failure mode you will meet in TypeScript. The check covers the drawings, not the building. If the crew improvises and pours something other than what was drawn, an approved drawing proves nothing, and that is precisely what happens when data arrives at run time from a file, a form, or an HTTP response that no drawing ever described. Worse, the checker can be talked into a stamp: hand over a sheet annotated "steel to supplier's specification, trust us" and there is nothing left to check. A building that passed plan check can still fall down. It just falls down for reasons the drawings did not contain.


Syntax or Core Structure

A TypeScript file is a JavaScript file with type annotations added. An annotation sits after a colon. The compiler, tsc, reads the annotations, complains when the code contradicts them, and then throws them away.

// greet.ts
function greet(name: string, times: number): string {
    const line = "Hello, " + name + "!";
    return Array.from({ length: times }, () => line).join("\n");
}

console.log(greet("Ada", 3));
console.log(greet("Grace", 1));

Compile it, then run the JavaScript that comes out:

tsc greet.ts
node greet.js

Output:

Hello, Ada!
Hello, Ada!
Hello, Ada!
Hello, Grace!

Three annotations are doing work in that file. name: string and times: number constrain what a caller may pass. The : string after the parameter list constrains what the function may hand back, which is why the compiler would object if the body lost its return. Everything else is ordinary JavaScript: Array.from, the arrow function, and join would behave identically in a .js file.

Now break it on purpose, one mistake per call:

console.log(greet("Ada", "3"));
console.log(greet(3, 1));

Output (tsc 5.4; each message is prefixed by a file, line and column, trimmed here):

error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

Note what still happened: greet.js was written anyway. By default tsc emits output even when it has found errors, on the theory that you may want to run the parts that are fine. --noEmitOnError turns that off, and almost every project should.


Technical Depth: The Two Timelines

Every question about TypeScript reduces to one question: does this happen at check time or at run time. Nothing crosses that line by accident.

What survives compilation

What you write in a .ts fileWhat appears in the emitted .js
A parameter or return annotationNothing; only the parameter name survives
An interface declarationNothing; it disappears entirely
A type aliasNothing; it disappears entirely
A generic type parameterNothing; there is no run-time type argument
An as assertion or a ! non-null assertionNothing; the expression is emitted unchanged
A classA real class, with its annotations stripped
An enum that is not constA real object, built by a small helper
A declare statementNothing; it was a promise about code elsewhere

That table is the whole trick, and it answers the question every newcomer asks first. You cannot test at run time whether a value "is a Point", because by then there is no Point left to test against.

Erasure, demonstrated

// erasure.ts
interface Point { x: number; y: number; }

function lengthOf(p: Point): number {
    return Math.sqrt(p.x * p.x + p.y * p.y);
}

const corner: Point = { x: 3, y: 4 };
console.log("length: " + lengthOf(corner));
console.log("typeof corner: " + typeof corner);
console.log("keys: " + Object.keys(corner).join(","));

Output:

length: 5
typeof corner: object
keys: x,y

Compiled with tsc --target es2020 erasure.ts, the emitted file contains the function, the object literal and the three log calls. The interface is not commented out and not replaced by a stub; it is simply absent. typeof answers object, exactly as it would for any other object literal, and Object.keys sees the two properties that were really assigned.

Inference does most of the work

Annotating every binding is a beginner habit worth dropping early. The compiler infers a type from the initialiser, and the inferred type is often more precise than the one a person would have written.

let city = "London";     // inferred: string
const port = 8080;       // inferred: the literal type 8080
let ready = false;       // inferred: boolean
const nums = [1, 2, 3];  // inferred: number[]
city = "Leeds";
nums.push(4);

console.log(city + ":" + port + " ready=" + ready);
console.log("sum=" + nums.reduce((a, b) => a + b, 0));

Output:

Leeds:8080 ready=false
sum=10

Two details there matter later. let city is inferred as string, so it will accept any other string, while const port is inferred as the literal type 8080, because a const can never hold anything else. And nums is a number[] whose contents changed freely: const protects the binding, never the object the binding points at.

The commands you will actually type

CommandWhat it does
tscCompiles the whole project according to tsconfig.json
tsc --initWrites a starter tsconfig.json with most options commented out
tsc --noEmitType-checks and writes no files, which is what belongs in CI
tsc --watchRe-checks on every save
tsc --noEmitOnErrorRefuses to write output when any error was found
tsx script.tsRuns one file by stripping types, with no type check at all

The last row is the one that surprises people. Modern runners such as tsx, esbuild, swc and Vite do not type-check. They delete the annotations and run whatever is left, which is exactly why they are fast, and Node itself can now strip types from a .ts file (experimentally from v22.6, on by default in newer releases). Every one of them will happily run code the compiler would have rejected, so a project built on one of them still needs tsc --noEmit somewhere in its pipeline. Checking and running are separate jobs done by separate programs.

Where the guarantee stops

An annotation is a claim about a value, and the compiler can only check claims it can see. The moment a value enters your program from outside, the claim becomes an act of faith:

type User = { id: number; name: string };

const raw = '{"id":"7"}';
const user = JSON.parse(raw) as User;

console.log("id is a " + typeof user.id);
console.log("name is " + user.name);

Output:

id is a string
name is undefined

Not one line of that is a compiler bug. JSON.parse is declared to return any, the as User told the checker to stop asking, and from there on the checker believes user.id is a number while the running program holds the string "7". The drawings were approved. The site poured something else.


Real World Example: A Goods-In Report That Trusts Its Input

// goods-in.ts
type Crate = { ref: string; count: number; kgEach: number };

const RAW = '[{"ref":"AX-11","count":4,"kgEach":12},{"ref":"BX-07","count":2,"kgEach":30},' +
            '{"ref":"CX-02","count":9,"kgEach":5}]';

function loadCrates(raw: string): Crate[] {
    return JSON.parse(raw) as Crate[];
}

function totalKg(c: Crate): number {
    return c.count * c.kgEach;
}

function pad(text: string, width: number): string {
    return text + " ".repeat(Math.max(0, width - text.length));
}

function report(crates: Crate[], limitKg: number): string {
    const lines: string[] = [];
    lines.push(pad("REF", 8) + pad("CRATES", 8) + pad("KG", 8) + "FLAG");
    let grand = 0;
    for (const c of crates) {
        const kg = totalKg(c);
        grand += kg;
        const flag = kg > limitKg ? "OVER" : "ok";
        lines.push(pad(c.ref, 8) + pad(String(c.count), 8) + pad(String(kg), 8) + flag);
    }
    lines.push(pad("TOTAL", 8) + pad("", 8) + pad(String(grand), 8) + "kg");
    return lines.join("\n");
}

console.log(report(loadCrates(RAW), 50));

Output:

REF     CRATES  KG      FLAG
AX-11   4       48      ok
BX-07   2       60      OVER
CX-02   9       45      ok
TOTAL           153     kg

Read it from the bottom up. report is handed a list of crates and a limit and returns a string; nothing inside it prints. That is deliberate. A function that returns its text can be tested by comparing two strings, while a function that prints can only be tested by capturing a stream. pad exists because fixed-width columns are easier to scan than commas, and totalKg exists because "crates times weight each" is the one piece of domain arithmetic in the program and deserves a name of its own.

The annotations earn their keep in two specific places. pad(String(c.count), 8) needs the explicit String(...) because c.count is a number and pad accepts only a string; in plain JavaScript the same call would have quietly returned "4" with no padding at all, because (4).length is undefined, 8 - undefined is NaN, and " ".repeat(NaN) is the empty string. The second place is grand += kg. Because totalKg is declared to return a number, the compiler holds its body to that promise, so if someone edits it to return c.count + "kg" the error lands on the function itself rather than three screens away as a total that reads 048.

Changing the program is where the checking pays out. Raise the limit to 60 and BX-07 flips from OVER to ok, because the comparison is greater-than rather than greater-or-equal; that is a one-character decision the type system cannot make for you. Add a required palletId: string field to Crate and every literal that builds a crate is flagged immediately, which is the behaviour you want. Notice what is not flagged, though: loadCrates keeps compiling, because no literal is involved there at all.

Now the genuine limits, starting with the real design flaw. loadCrates is a stamp on an unread drawing: JSON.parse(raw) as Crate[] promises the compiler something nobody verified. Delete kgEach from the second record and the program still compiles and still runs, but c.count * undefined is NaN, so the KG column prints NaN, the total prints NaN, and since NaN > 50 is false every row is flagged ok. A silently wrong goods-in report is worse than a crash, and the annotation is what made it silent. Three smaller weaknesses follow: pad never truncates, so a ref of eight characters or more pushes the remainder of its row out of alignment; the limit is compared per line, so four under-limit crates bound for one lorry are never flagged; and String(kg) is tidy for integers and ugly the moment a weight is fractional. Only the first of those is a design flaw. It is also the only one the compiler cannot help with.


Common Mistakes

  1. Treating tsc as a way to run code. tsc is a checker and a translator, not a runtime. It reads .ts and writes .js, and something else has to execute the result. Newcomers who type tsc app.ts and wait for output are waiting for a program that has already finished.
  2. Reaching for any to make a red squiggle go away. any does not solve the disagreement between you and the compiler; it ends the conversation. Every property access, call and arithmetic operation on an any is unchecked from that point outward, and the unchecked region tends to spread along the data flow.
  3. Believing an annotation validates incoming data. JSON.parse, fetch, localStorage, process.env and a form submission all deliver values the compiler never saw. An annotation on the receiving variable describes your hope, not the bytes.
  4. Using as as though it converted something. An assertion changes the compiler's opinion and emits no code whatsoever. ("7" as unknown as number) + 1 produces the string "71" at run time, with no error anywhere.
  5. Annotating every binding. const port: number = 8080 is worse than const port = 8080, because the annotation widens the inferred literal type 8080 back to number and adds a second place to edit. Annotate the boundaries -- parameters, return types, exported values -- and let inference handle the interior.
  6. Assuming errors stop the build. By default tsc reports its errors and writes the output anyway. Without noEmitOnError, a broken commit still produces runnable .js, which is how a type error reaches production untouched.
  7. Mistaking a bundler for a type-checker. Vite, esbuild, swc and tsx strip annotations without reading them. A project that only ever runs those has no type checking in it at all, however many .ts files it contains.
  8. Leaving strict off. With strictNullChecks disabled, null and undefined belong to every type, so the largest single category of JavaScript run-time errors goes unreported. A non-strict TypeScript project pays the syntax cost and collects a fraction of the benefit.
  9. Expecting run-time tests against an interface. value instanceof Point will not compile when Point is an interface, because there is no Point at run time to compare against. Run-time checks have to be written against things that survive compilation: properties, typeof, or a class.

Best Practices

  • Start every new project with strict: true. Turning strictness on later means fixing hundreds of pre-existing errors at once, and the pressure to skip that work with any is enormous. On day one the cost is zero.
  • Run tsc --noEmit in CI even when nothing in production uses tsc. Whatever transpiles your code for speed, one job somewhere must actually read the types, or the annotations are decoration.
  • Annotate the boundaries and let inference fill the interior. Function parameters, return types and exported values are worth writing down because they are contracts; local variables usually are not.
  • Validate once, at the edge. Every value that enters from a network, a file, an environment variable or a form should pass through one function that checks it and returns a known shape. Inside that line you can trust the types; outside it you cannot.
  • Prefer unknown over any when you genuinely do not know. Both accept anything, but unknown refuses to be used until you have narrowed it, which converts a silent hole into a compiler error at the exact place a check is missing.
  • Keep the checker in your edit loop. tsc --watch in a terminal, or the editor's language server, means errors arrive while the code is still in your head instead of ten minutes later in a build log.
  • Treat every as as a claim that needs a reason. A short comment saying why the assertion is safe is worth more than the assertion, and a file with a dozen of them is a file worth re-reading.
  • Pin the TypeScript version in devDependencies and commit tsconfig.json. Minor releases add new checks, so a floating version can break the build with no change to your code, and a shared config is what stops "it compiles on my machine".

Practice Exercises

  1. Watch erasure happen. Save the erasure.ts example, compile it with tsc --target es2020 erasure.ts, open the emitted .js, and list every line that differs from the source. Then add an enum with three members, compile again, and explain in one sentence why that declaration did not disappear when the interface did.
  2. Make the report lie, then stop it. Take goods-in.ts, remove kgEach from the second record in RAW, run it, and write down the exact output including the total line. Then replace the body of loadCrates with a loop that checks each field and throws an error naming the offending ref, and describe how the failure differs for someone reading the console at 2am.
  3. Prove the emit-on-error default. Introduce one type error, run tsc, and confirm the .js file was written anyway; record the process exit code. Then run it again with --noEmitOnError and confirm no file appears. Decide which of the two you want in a pre-commit hook, and say why.
  4. Type-check code that already works. Rename any small .js file you own to .ts and run tsc --noEmit --strict on it. Write down the first five errors, and for each one mark whether it is a real bug, a place where the compiler needs an annotation, or a genuine false alarm. Most people find at least one real bug in their first file.