The Programming Shortcut: TypeScript
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about static checking as a tool you choose.
TypeScript is JavaScript with a checker standing next to you.
That’s most of what it is. Every TypeScript program is a JavaScript program with
some notes written into it, notes that say what kind of value goes where. A tool
called tsc reads those notes, reads your code, and tells you where the two
disagree. Then it deletes the notes and hands you plain JavaScript to run.
So TypeScript doesn’t ask you to learn a new way of programming. It asks you to say out loud what you were already assuming, and then it holds you to it. And it lets you decide how much to say, and how hard it should look. That choice is what this article is about: static checking as a tool you pick up, and types as a way to design a program before you run it.
What you already have
TypeScript’s everyday code is JavaScript’s, and JavaScript’s everyday code looks
like most languages you’ve met. Variables are const and let. Functions,
if, for, while, arrays in square brackets, and objects in curly braces all
look the way you’d guess, so this article won’t slow down for any of them.
What’s new is the vocabulary for describing values:
| What you know | lux | TypeScript |
|---|---|---|
| a record | struct Parcel { kg: float } | type Parcel = { kg: number } |
| a value that might be missing | Option<int> | number | undefined |
| one of a fixed set of cases, each with its own data | enum with payloads | a union of object types with a shared tag field |
| covering every case | match, checked | switch, checked with a never trick |
| when types are checked | before every run, always | when you run tsc, then erased |
If you learned lux, you’ve already used a checker. You just never got a say in it: lux checks every program, every time, before anything runs. TypeScript hands you the switch, and a dial for how hard it looks. The rest of this article works the same whether or not you’ve ever seen lux.
Save, read, run
You’ll need Node.js, the program that runs JavaScript outside a browser. With it installed, one command gets you the checker, using npm, the package manager that comes with Node.js:
npm install -g typescript
(The TypeScript download page has the other ways.)
Make a folder, and in it a file called hello.ts with a mistake on purpose:
const greeting: string = 42;
console.log(greeting);
The : string is a type annotation: a note that says what kind of value
greeting should hold. Now open a terminal in that folder and start the
checker in watch mode:
tsc --watch hello.ts
It reads the file and answers right away:
03:33:33 PM - Starting compilation in watch mode...
hello.ts(1,7): error TS2322: Type 'number' is not assignable to type 'string'.
03:33:33 PM - Found 1 error. Watching for file changes.
Line 1, column 7: you promised a string and gave it a number. Leave that
terminal running, and look in the folder. There’s a new file, hello.js, even
though there was an error. That file comes back near the end of this article.
Fix the line to const greeting: string = "hello"; and save. The watching
terminal notices, checks again, and reports Found 0 errors. Open a second
terminal in the same folder and run what it wrote:
node hello.js
From here on, the rhythm is save, read the errors, run. The first
terminal is your checker, always watching. The second is where the program
actually runs. Every time something new appears below, try it in hello.ts and
watch the first terminal before you run anything.
The checker reads, it never runs
A checker is a program that reads your program without running it and looks for contradictions. That’s what “static” means in static checking: the code sits still while it’s examined. Nothing gets printed, nothing gets saved, no branch gets taken. Every line is read, including the ones that would never run today.
The surprise is how much it can work out with no help at all. Try this, with no annotations anywhere:
const parcel = { id: "A1", kg: 2.5 };
console.log(parcel.weight * 2);
error TS2339: Property 'weight' does not exist on type '{ id: string; kg: number; }'.
You never said what type parcel was. The checker looked at the value you gave
it and wrote the type down for itself: an object with an id that’s a string
and a kg that’s a number. This is called type inference, the checker
deducing types from the values in front of it. In plain JavaScript, that line
quietly prints NaN, short for “not a number,” and carries on.
Inference covers the inside of your code very well. Where it runs out is at the
edges, where a value arrives from somewhere the checker can’t see. A function’s
parameters are the main edge: when you write function shippingCost(kg), the
checker has no idea what callers will pass. So that’s where you write
annotations:
function shippingCost(kg: number): number {
return 4 + kg * 1.5;
}
console.log(shippingCost(2));
The : number after kg says what comes in. The : number after the
parentheses says what goes out. Inside the function, everything else is
inferred. A good rule of thumb is that you annotate the edges and let the
checker work out the middle.
How strict? You decide
Here’s a small program with a bug. find looks through an array and returns the
first match, or undefined if there isn’t one. JavaScript’s undefined means
“no value here,” and it’s the closest thing TypeScript has to an empty Option
(the idea of a value that might be missing gets its full treatment in the
Rust article). Save it as found.ts:
const ids = ["A1", "B2"];
const found = ids.find((id) => id.startsWith("C"));
console.log(found.length);
error TS18048: 'found' is possibly 'undefined'.
The checker inferred that found is string | undefined, read as “a string or
undefined.” The | builds a union type: a value that’s one of several types.
Since nothing starts with “C,” found really is undefined, and asking for its
length would crash.
Now run the same file with the checker turned down:
$ tsc --strict false found.ts
$ node found.js
TypeError: Cannot read properties of undefined (reading 'length')
No error from tsc, and a crash when it runs. With strict off, the checker
treats undefined as something that fits anywhere, so it stops asking. It also
stops complaining about parameters with no annotation, and lets them accept
anything at all.
That’s the dial. strict is a bundle of stricter checks, and since TypeScript
6.0 it’s on unless you turn it off. You can also turn its parts on and off one
at a time, with flags such as --strictNullChecks for the undefined question.
Why would anyone turn it down? Because TypeScript was built for people with
thousands of lines of JavaScript already written. Turning everything on at once
would bury them in errors, so they turn the checks up a notch at a time, file by
file, as the code gets cleaned up. Starting fresh, leave it on.
When the checker does complain, the fix is to handle the case:
const ids = ["A1", "B2"];
const found = ids.find((id) => id.startsWith("C"));
if (found === undefined) {
console.log("no match");
} else {
console.log(found.length);
}
Inside the else, the checker knows found is a string, because it followed
your if. This is called narrowing: a check in your code shrinks a union down
to the cases that are still possible. Narrowing is how a checker and an ordinary
if work together, and the rest of this article leans on it.
Types are a design you write down
So far the checker has been catching slips: a misspelled property, a missing value. That’s useful, and it’s the smaller half of the story. The bigger half is that types let you write down what your data is allowed to be, before you write any code that uses it. Then the checker holds every line to that design.
Say a shop takes three kinds of payment: cash, a card (where you keep the last four digits), or a voucher (where you keep its code). The quick way to describe that is one record with every field anyone might need:
type Payment = { kind: string; last4?: string; code?: string };
const payment: Payment = { kind: "card" };
console.log(`Card ending ${payment.last4}`);
The ? makes a field optional, and the backticks make a template string, where
${...} drops a value into the text. This passes the checker and prints Card ending undefined. Nothing is wrong according to the type, because the type allows it.
It also allows a cash payment with a card number, a voucher with no code, and a
kind of "check". The type describes a shape, but it doesn’t describe the
shop.
Here’s the design written down instead:
type Payment =
| { kind: "cash" }
| { kind: "card"; last4: string }
| { kind: "voucher"; code: string };
function receipt(payment: Payment): string {
switch (payment.kind) {
case "cash":
return "Paid in cash";
case "card":
return `Card ending ${payment.last4}`;
case "voucher":
return `Voucher ${payment.code}`;
}
}
console.log(receipt({ kind: "card", last4: "4242" }));
Two new ideas are in there. First, "cash" is used as a type. A literal type
is a type with one value in it: the only string that fits "cash" is "cash".
Second, Payment is a union of three object types, each with a kind field
holding a different literal. That shared field is called the tag, and a union
told apart by its tag is a discriminated union. It’s TypeScript’s version of a
sum type, a value that’s one of a fixed set of cases, each carrying its own data
(sum types have their home in the Rust article).
Now look at what the checker knows. Inside case "card":, it has narrowed
payment to the card case, so payment.last4 is a string, guaranteed. Try to
read payment.code there and it refuses, since cards don’t have one. And the
nonsense values are gone:
type Payment =
| { kind: "cash" }
| { kind: "card"; last4: string }
| { kind: "voucher"; code: string };
const payment: Payment = { kind: "card" };
console.log(payment);
error TS2322: Type '{ kind: "card"; }' is not assignable to type 'Payment'.
Property 'last4' is missing in type '{ kind: "card"; }' but required in type '{ kind: "card"; last4: string; }'.
A card without its digits can’t be written down anymore. People put this as
“make illegal states unrepresentable”: design the type so the wrong value has no
spelling, and you never have to check for it later. A misspelled tag fails the
same way. Write kind: "vouchr" and the checker says the value isn’t one of the
three, and usually suggests the one you meant.
Look back at the two Payment types. The first was a description of some JavaScript objects. The
second is a short, checkable statement of how the shop works, and you can read
it before reading a single function.
Making the checker find what you forgot
Designs change. Say the shop starts taking store credit. You add a case to the
type and move on, and somewhere in the program a switch is still handling
only the old three. Can the checker find it for you?
It can, with one small function:
type Payment =
| { kind: "cash" }
| { kind: "card"; last4: string }
| { kind: "voucher"; code: string }
| { kind: "credit"; account: string };
function unreachable(value: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(value)}`);
}
function receipt(payment: Payment): string {
switch (payment.kind) {
case "cash":
return "Paid in cash";
case "card":
return `Card ending ${payment.last4}`;
case "voucher":
return `Voucher ${payment.code}`;
default:
return unreachable(payment);
}
}
console.log(receipt({ kind: "cash" }));
error TS2345: Argument of type '{ kind: "credit"; account: string; }' is not assignable to parameter of type 'never'.
never is the type with no values in it at all. Nothing fits. Each case
narrows payment a little further, and by the default, every case you handled
has been ruled out. If you handled them all, what’s left is never, and passing
it to unreachable is fine. If you missed one, what’s left is that case, and
the checker names it for you. Add a case "credit": and the error goes away.
That’s exhaustive matching: the checker proving you covered every case. Some
languages build it in (the Rust article is its home); in TypeScript
it’s a habit you choose, one default line per switch. In a big program, that
one line turns “add a case to the type” into a list of every place that needs
updating, delivered before you run anything.
Then the types disappear
Remember the hello.js that appeared even though there was an error? Here’s
what tsc writes for the receipt function above:
function receipt(payment) {
switch (payment.kind) {
case "cash":
return "Paid in cash";
case "card":
return `Card ending ${payment.last4}`;
The types are gone. This is called type erasure: the types exist only while
tsc is checking, and the program that runs has none of them. The checker
writes the JavaScript whether or not it found errors, because its job is to
advise you, not to stop you. (The "use strict" line you’ll see at the top of
its output is JavaScript’s own setting, and nothing to do with the checker’s.)
Erasure is what makes TypeScript so easy to adopt. The output is ordinary
JavaScript, so it runs anywhere JavaScript runs. Node.js will even run a .ts
file directly, by blanking out the types and running what’s left, without
checking anything. But it’s also where TypeScript gives up a guarantee you may
be used to. In a language like lux or Rust, a value that claims to be a number
is a number. In TypeScript, it’s a number if everything that touched it was
checked. Data from outside, such as a file or a network reply, wasn’t:
type Parcel = { id: string; kg: number };
const parcel: Parcel = JSON.parse('{ "id": "A1", "kg": "2.5" }');
console.log(parcel.kg + 1);
That prints 2.51. JSON.parse turns text in JSON (JavaScript Object
Notation, the most common format for sending data as text) into a value, and
the checker can’t know what the text will hold, so it calls the result any. any is a type that
switches checking off: anything fits into it, and it fits into anything. Here it
slid straight into a Parcel, and a string got treated as a number with no
complaint. The program ran with the wrong value in a field that promised better.
Beware of any. It’s the one-word way to make an error go away, and you’ll
see it all over answers online, pasted in to silence a checker someone was
tired of reading. Every any is a hole in the design, and holes spread: a value
typed any passes its blindness to everything it touches. When you truly don’t
know what something is, write unknown instead. It’s the careful sibling of
any: anything fits into it, but the checker won’t let you use it until you’ve
narrowed it with a check of your own. An error you silence with any is a bug
you’ve scheduled for later.
A parcel list that lies to you
Here’s a small program in plain JavaScript. It keeps a list of parcels, says
where each one is, and adds up their weight. Save it as parcels.js in a new
folder:
const parcels = [
{ id: "A1", status: "packed", kg: 2.5 },
{ id: "B2", status: "shipped", kg: 1.2, tracking: "1Z999" },
{ id: "C3", status: "delivered", kg: "4", tracking: "1Z123", deliveredOn: "Nov 20" },
{ id: "D4", status: "shipped", kg: 0.8 },
];
function describe(p) {
switch (p.status) {
case "packed":
return `${p.id}: packed, waiting for pickup`;
case "shipped":
return `${p.id}: on its way, tracking ${p.tracking}`;
case "deliverd":
return `${p.id}: delivered ${p.deliveredon}`;
default:
return `${p.id}: status unknown`;
}
}
let total = 0;
for (const p of parcels) {
console.log(describe(p));
total += p.kg;
}
console.log(`Total weight: ${total} kg`);
Run it with node parcels.js:
A1: packed, waiting for pickup
B2: on its way, tracking 1Z999
C3: status unknown
D4: on its way, tracking undefined
Total weight: 3.740.8 kg
No errors, and three bugs. A delivered parcel has an unknown status. A shipped
parcel has no tracking number. And the total weight is a sentence, not a number,
because one weight was written as the text "4" and + glued the rest on as
text. JavaScript did what it was told every step of the way.
Step 1: check it as it is. You don’t have to change a line to get a first opinion. Start the checker on the JavaScript file:
tsc --watch --checkJs --noEmit parcels.js
--checkJs asks it to check a JavaScript file, and --noEmit tells it not to
write any output, since this file is already JavaScript. It finds two things:
parcels.js(8,19): error TS7006: Parameter 'p' implicitly has an 'any' type.
parcels.js(24,3): error TS2365: Operator '+=' cannot be applied to types 'number' and 'string | number'.
The second error is the weight bug, found purely by inference: the checker
noticed that kg is sometimes a number and sometimes a string. Change "4" to
4 and save, and it’s gone.
The first error is the checker telling you where it’s blind. It can’t know what
p is inside describe, so it treats it as any and checks nothing there.
That’s why it missed the other two bugs. Inference has taken you as far as it
can. The rest needs a design.
Step 2: write the design down. Stop the watcher with Ctrl+C. Rename
parcels.js to parcels.ts, and add this at the top, followed by a blank line:
type Parcel =
| { status: "packed"; id: string; kg: number }
| { status: "shipped"; id: string; kg: number; tracking: string }
| { status: "delivered"; id: string; kg: number; tracking: string; deliveredOn: string };
That’s the business rule, in four lines: a parcel is in one of three states, and
shipped and delivered parcels always have a tracking number. Now tell the
program about it. Change the first line of the list to
const parcels: Parcel[] = [, which says the array holds parcels, and give
describe its annotations, function describe(p: Parcel): string {. Then start
the checker on the new file:
tsc --watch parcels.ts
parcels.ts(10,3): error TS2322: Type '{ id: string; status: "shipped"; kg: number; }' is not assignable to type 'Parcel'.
Property 'tracking' is missing in type '{ id: string; status: "shipped"; kg: number; }' but required in type '{ status: "shipped"; id: string; kg: number; tracking: string; }'.
parcels.ts(19,10): error TS2678: Type '"deliverd"' is not comparable to type '"delivered" | "packed" | "shipped"'.
(It also reports two errors on line 20 about a type called never, which go
away with the typo.) There are both remaining bugs. Parcel D4 claims to be
shipped without a tracking number, and "deliverd" isn’t a status that exists.
Give D4 a tracking number, tracking: "1Z456", fix the spelling to
"delivered", and save. The checker has two more:
parcels.ts(20,38): error TS2551: Property 'deliveredon' does not exist on type '{ status: "delivered"; id: string; kg: number; tracking: string; deliveredOn: string; }'. Did you mean 'deliveredOn'?
parcels.ts(22,19): error TS2339: Property 'id' does not exist on type 'never'.
The first is a third bug that was hiding behind the second: the wrong
capitalization of deliveredOn. Fix it. The second is the checker pointing out
that the default can’t happen anymore, because every status is handled. That’s
your cue for the never trick. Add the unreachable function above describe:
function unreachable(p: never): never {
throw new Error(`Unhandled parcel: ${JSON.stringify(p)}`);
}
and make the default return unreachable(p);. Save, and the first terminal
says Found 0 errors. Run the result in the second terminal with
node parcels.js:
A1: packed, waiting for pickup
B2: on its way, tracking 1Z999
C3: delivered Nov 20
D4: on its way, tracking 1Z456
Total weight: 8.5 kg
parcels.js is back, and this time tsc wrote it: your program with the types
erased.
Step 3: change the design. Customers start sending things back. Add a fourth
case to the type, and move the ; from the old last line to this new one:
| { status: "returned"; id: string; kg: number; reason: string };
and a returned parcel to the list, { id: "E5", status: "returned", kg: 3.1, reason: "wrong size" },. Save. The checker points straight at the default in
describe, naming the "returned" case you haven’t handled. Add it:
case "returned":
return `${p.id}: sent back (${p.reason})`;
Zero errors, and node parcels.js prints five parcels and a total of 11.6 kg.
You changed the design first, and the checker walked you to the code that had to
follow. The finished file is in
projects/typescript/parcels.ts, with
more experiments at the bottom.
What’s left out
A lot of TypeScript isn’t here. Generics, which let one type or function work
across many types, are a big part of real TypeScript; they’re the subject of the
Swift article, and TypeScript’s work the same way in spirit.
interface, which overlaps heavily with type, is skipped, and so are classes,
modules, tsconfig.json files, and the long list of individual strict flags.
There’s also a whole type-level programming language hiding inside TypeScript,
with mapped and conditional types, which you won’t need for a long time and may
not need at all.
All of it is skipped because none of it changes the idea. You choose a checker, you choose how strict it is, you write your design as types, and you let it hold your code to that design until the types are erased.
When you want more, the TypeScript Handbook is written by the people who make the language, and its chapter on narrowing picks up where this article stops.
One last thing to try
Go back to your finished parcels.ts and run the checker one more time, with a
flag that asks it to show its work:
tsc --declaration parcels.ts
Next to parcels.js, there’s now a parcels.d.ts. Read it. It holds every type
in your program, including the ones you never wrote, like the type of total.
Then open parcels.js and look for those same types. Bring this question: which
of the types in the first file did the checker work out on its own, and where
did all of them go?
Related
- Rust, for values that might be missing, sum types and exhaustive matching, built into the language.
- Swift, for generics.
- JavaScript, for the language underneath all of this.
Tested with TypeScript 7.0.2 and Node.js 26.13.1, November 2026.