The Analogy: Re-laying a Working Railway Line During Engineering Hours
A busy railway cannot close for a month while worn rail is replaced, because trains run every morning and the line is needed. So the permanent-way gang re-lays it a section at a time during engineering hours at night, and each morning the line reopens carrying traffic over a mix of new rail and old, the trains crossing the joins without noticing. The whole route is never all-new until the last section is done, and that is perfectly acceptable. A TypeScript migration works the same way: you do not rename every file to .ts in one go, you convert a section at a time while the application keeps shipping, and .js and .ts files run side by side across the join for as long as it takes.
The coexistence is deliberate engineering, not a grudging compromise. Old and new rail are bolted together with fishplates so a train crosses from one to the other transparently, and the signalling treats the mixed line as one line. TypeScript is built the same way: with allowJs turned on, .js and .ts files import one another freely and nothing that used to work stops working. The gang's first night is not spent laying any new rail at all; it is spent setting up the depot and the possession arrangements so that work can proceed safely later. A migration's day one is the same, a tsconfig with allowJs on and strictness off, committed on its own, changing nothing for anyone.
Order matters on the track as much as in the code. The gang re-lays the quiet sidings and approach sections first, where a mistake strands nothing important and the method can be learned, before touching the busy junction that everything depends on. A migration converts bottom-up in exactly this spirit: the leaf utilities, constants, and pure functions with the fewest dependencies go first, so that by the time you reach the tangled parts, the things they import are already typed and inference does most of the work for you. And the speed limit over freshly laid rail is raised in stages as it beds in, never straight to full line speed; the strict compiler flags are turned on one at a time, each wave finished before the next begins, rather than all at once.
The failure mode is the total blockade: closing the whole line and re-laying everything in one heroic possession. It almost never goes to plan, the possession overruns, the line stays shut far longer than promised, and management orders it reopened on the old rail with the job abandoned. Renaming every file to .ts on a Friday is that blockade, producing thousands of errors, nothing shippable, and a reverted branch on Monday. The temporary speed restrictions the gang leaves on unfinished sections are honest and self-removing, lifted the moment the section is signed off; the escape hatches in a migration should be the same, narrow and visible so they get removed, not a blanket any that quietly becomes permanent. The goal is never "all new rail by Friday"; it is "every new section is proper, and the old improves as we reach it."
Syntax or Core Structure
The day-one move is a permissive config that lets .js and .ts coexist, changing nothing about what compiles. Only then do you convert leaf files one at a time. A converted utility looks like ordinary typed code, and it runs exactly as its JavaScript predecessor did.
{
"compilerOptions": {
"allowJs": true,
"checkJs": false,
"strict": false,
"noEmit": true
},
"include": ["src"]
}
allowJs: true with checkJs: false is the whole day-one configuration: nothing breaks, nothing new is checked, and you can start writing .ts immediately. Here is a leaf utility after conversion, using integer minor units so the totals stay exact:
// src/cart.ts -- a converted leaf utility
interface CartItem {
id: string;
price: number;
qty: number;
}
function total(items: readonly CartItem[], taxPercent: number): number {
const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0);
return subtotal + Math.trunc((subtotal * taxPercent) / 100);
}
const items: CartItem[] = [
{ id: "a", price: 200, qty: 2 },
{ id: "b", price: 150, qty: 1 },
];
console.log(items.length);
console.log(total(items, 20));
console.log(total(items, 0));
Output:
2
660
550
The subtotal is 200 * 2 + 150 * 1 = 550. At a taxPercent of 20, the tax is Math.trunc(550 * 20 / 100) = 110, so the total is 550 + 110 = 660. At a taxPercent of 0 there is no tax and the total is the bare subtotal, 550. The readonly CartItem[] parameter documents that total does not mutate the cart, which is a piece of intent the original untyped JavaScript could only express in a comment.
Technical Depth: The Bugs a Rename Surfaces, and the Flag Order
The real return on a migration is not that code becomes typed; it is that the compiler names existing assumptions that were never true. Two classic bugs surface almost every time, and the strict flags that reveal them are best enabled in a deliberate order.
The missing-argument bug a default fixes
In untyped JavaScript a function called with a missing numeric argument silently computes with undefined, producing NaN. Typing the parameter, with a default, makes the intent explicit and the result correct.
// src/tax.ts
function withTax(subtotal: number, taxPercent = 0): number {
return subtotal + Math.trunc((subtotal * taxPercent) / 100);
}
console.log(withTax(500, 10));
console.log(withTax(500));
console.log(withTax(500, 10) + withTax(500));
Output:
550
500
1050
withTax(500, 10) adds Math.trunc(500 * 10 / 100) = 50 for 550. withTax(500) omits the second argument, so the default taxPercent = 0 applies and the result is the bare 500 rather than the NaN the untyped version would have produced. Their sum is 550 + 500 = 1050. The default parameter is the fix the rename made visible.
The undefined-return bug strictNullChecks names
A lookup that can fail returns T | undefined, and under strictNullChecks every caller that assumed a hit is flagged. Handling the miss explicitly is the fix.
// src/find.ts
interface CartItem {
id: string;
price: number;
}
function findItem(items: CartItem[], id: string): CartItem | undefined {
return items.find((item) => item.id === id);
}
function priceOf(items: CartItem[], id: string): number {
const item = findItem(items, id);
return item === undefined ? -1 : item.price;
}
const items: CartItem[] = [
{ id: "a", price: 200 },
{ id: "b", price: 150 },
];
console.log(priceOf(items, "a"));
console.log(priceOf(items, "z"));
console.log(priceOf(items, "a") + priceOf(items, "b"));
Output:
200
-1
350
priceOf(items, "a") finds the item and returns its price 200. priceOf(items, "z") finds nothing, so findItem returns undefined and the guard returns the sentinel -1 instead of crashing on item.price. The last line adds the prices of "a" and "b", 200 + 150 = 350. Before strictNullChecks, a caller writing findItem(items, id).price compiled cleanly and was one missing item away from a runtime crash; the flag names every such call site.
The order to enable strict flags
The strict family is best turned on one flag at a time, each as its own finishable job, laid out below in a sensible order.
| Flag | What it forces | Typical wave size |
|---|---|---|
| noImplicitAny | annotate untyped parameters | usually the largest |
| strictNullChecks | handle null and undefined | the most valuable, do alone |
| strictFunctionTypes | check parameter variance | small |
| noImplicitThis | type the this parameter | small |
| useUnknownInCatchVariables | narrow caught errors | small |
Reading the wave-size column, noImplicitAny clears the most and comes first, strictNullChecks is where the real bugs hide and deserves its own branch, and the rest are small tidy-ups. Enable strict: true only once each individual flag is already satisfied, so the final switch changes nothing.
Real World Example: One File's Journey to Typed
A checkout module is one converted section of the line. After conversion it computes line totals over a typed cart, looks a line up safely, and reports the totals with a grand total. The point is not that it is now typed but that the shapes it once assumed are now stated, and the miss case that would have crashed is now handled.
// src/checkout.ts
interface Line {
sku: string;
price: number;
qty: number;
}
function lineTotal(line: Line): number {
return line.price * line.qty;
}
function findLine(lines: Line[], sku: string): Line | undefined {
return lines.find((line) => line.sku === sku);
}
function pad(text: string, width: number): string {
const gap = width - text.length;
return text + " ".repeat(gap > 0 ? gap : 0);
}
const lines: Line[] = [
{ sku: "aa", price: 200, qty: 2 },
{ sku: "bb", price: 150, qty: 1 },
{ sku: "cc", price: 90, qty: 3 },
];
let grand = 0;
console.log("lines: " + lines.length);
console.log(pad("SKU", 6) + "TOTAL");
for (const line of lines) {
const value = lineTotal(line);
grand += value;
console.log(pad(line.sku, 6) + value);
}
const missing = findLine(lines, "zz");
console.log("missing: " + (missing === undefined ? "none" : missing.sku));
console.log("grand: " + grand);
Output:
lines: 3
SKU TOTAL
aa 400
bb 150
cc 270
missing: none
grand: 820
Trace the three lines. lineTotal multiplies price by quantity: 200 * 2 = 400, 150 * 1 = 150, and 90 * 3 = 270, so the grand total is 400 + 150 + 270 = 820. The lookup for "zz" finds nothing, and because findLine is typed to return Line | undefined, the guard prints missing: none rather than dereferencing undefined. Every value in the report is exact because prices and quantities are whole numbers.
The value of the conversion is that the two assumptions the JavaScript left implicit are now enforced: Line states the exact shape each function expects, and findLine's Line | undefined return forces the missing case to be handled at every call site. The compiler, not a test that happened to be written, is what guarantees the crash on a missing SKU can no longer compile.
The migration nonetheless leaves real limits, and they map straight onto the half-relaid line. Most importantly, the safety stops at the join: this file is typed, but any remaining .js caller can still hand it a malformed object, and TypeScript checks only the typed side, so the boundary between converted and unconverted code is exactly where a bad value still slips through, just as a derailment is likeliest at the fishplate between new rail and old. Two smaller limits sit alongside: a type describes shape, not value, so lineTotal will happily multiply a negative price or qty that no annotation forbids; and the missing case is signalled with the sentinel string "none" and the earlier priceOf used -1, magic values the type system does not police and that a Result type or a thrown error would express more honestly.
Common Mistakes
- Renaming every file at once. A big-bang conversion drowns you in thousands of errors with nothing shippable, and the usual result is a reverted branch.
- Starting with
strict: trueon a large JS codebase. Every strict check fires simultaneously, so there is no order in which to make steady, reviewable progress. - Migrating top-down from components. Converting a component before its data layer means hand-annotating everything that inference would have supplied from typed dependencies.
- Reaching for
anyas the default fix. It keeps the syntactic ceremony while discarding every benefit, and it tends to spread outward from where it was introduced. - Using
@ts-ignoreinstead of@ts-expect-error. The former lingers forever, whereas the latter errors once the underlying problem is fixed and so removes itself. - Not committing per file. A two-hundred-file diff cannot be reviewed or cleanly reverted, which defeats the point of incremental work.
- Skipping
@typespackages. Hand-writing declarations for a library that already ships types on DefinitelyTyped wastes effort and risks conflicts. - Trusting the typed side at the boundary with untyped code. A
.jscaller can still pass a malformed value, so the join between converted and unconverted files still needs a runtime check. - Treating the migration as a separate project. Interleaving it with feature work keeps it funded and moving; a standalone "migration quarter" tends to stall.
Best Practices
- Ship the permissive config on its own first. Turn on
allowJs, keepcheckJsandstrictoff, and commit that change alone so nothing breaks for anyone. - Require every new file to be
.tsfrom day one. Enforce it in review, and the untyped portion of the codebase shrinks on its own over time. - Convert bottom-up, one file per commit. Start with leaf utilities so their dependents inherit real types, and fix only that file's errors in each commit.
- Enable strict flags one at a time. Finish each wave before starting the next, and give
strictNullChecksits own branch because it surfaces the most bugs. - Prefer
as unknown as Xoveranyfor a temporary lie. It is narrow, ugly, and visible, which is exactly why it gets cleaned up later. - Use
@ts-expect-errorwith a note over@ts-ignore. A self-deleting suppression cannot outlive the problem it was hiding. - Validate at the boundary with untyped code. Treat the edge where
.tsmeets.jslike any other input boundary and check values crossing it at runtime. - Track a visible progress number. Files converted or
anycount on a dashboard keeps the work funded and shows it is actually finishing.
Practice Exercises
- The First Commit. Write the day-one
tsconfigfor a JavaScript project withallowJson and strictness off, and confirm that the type-check reports no new errors before any file is converted. - The Leaf. Convert a single utility file from
.jsto.ts, add a precise parameter and return type, and run it to confirm the behaviour is unchanged while the intent is now stated. - The Null Hunt. Give a lookup function a
T | undefinedreturn, enable the equivalent ofstrictNullChecksin your reasoning, and rewrite one caller to handle the miss instead of assuming a hit. - The Join. Take a typed function called by an untyped caller, describe where a malformed value could still enter, and add a runtime validation at that boundary so the typed side can trust its input.