Programming languages · Advanced · 25 min
Tighten an existing TypeScript project one strict check at a time
By Padding · Updated 18 Nov 2026
TypeScript 7.0.2 · Node.js 26.13 LTS · node:26 image
You will take a loose TypeScript 7 project from strict off to strict plus three extra checks, one flag at a time, with a script that counts errors and a CI ratchet that stops new ones getting in.
On this page
A new TypeScript project should start with "strict": true, as in the TypeScript 7 setup tutorial. Many real codebases did not. They grew with strict off, JavaScript files mixed in and any wherever a type was inconvenient. Turning strict on in one go there produces hundreds of errors, a pull request nobody can review, and usually a retreat.
This tutorial does it the slow way that works. You get a small, deliberately loose shop-cart project and turn checks on one at a time: noImplicitAny, strictNullChecks, strictFunctionTypes, the rest of strict, and then three checks that strict does not include. Before each flag you count the errors it would add. You fix each error properly, not with any or the ! non-null assertion, which hide the problem. A ratchet file records how many errors the target settings still produce, so CI can reject a change that adds new ones while you work.
One TypeScript 7 change matters here. Its release notes say strict is now true by default (Announcing TypeScript 7.0). If your project's tsconfig.json has no strict line and you upgrade, you get every strict error at once. Add "strict": false explicitly before the upgrade, then work through the flags as below.
Step 1 · Create the loose project
Make a throwaway project and install the compiler. --save-exact records 7.0.2 without a ^, because a later compiler can find more or fewer errors, and a count you compare in CI must come from the same compiler every time:
mkdir -p ~/ts-tighten-demo
cd ~/ts-tighten-demo
npm init -y
npm pkg set type=module
npm install --save-dev --save-exact typescript@7.0.2
npm install --save-dev @types/node@26
npx tsc --versionWrite the loose tsconfig.json. strict is off, allowJs lets .js files sit beside .ts files, and rootDir and types are set because TypeScript 7 changed their defaults:
cat > tsconfig.json <<'JSON'
{
"compilerOptions": {
"target": "es2023",
"module": "nodenext",
"rootDir": "src",
"outDir": "dist",
"strict": false,
"allowJs": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}
JSONNow the source. A catalogue with untyped parameters, prices kept in the smallest currency unit (kobo, cents or pesewas) so there are no rounding errors:
mkdir -p src scripts
cat > src/catalogue.ts <<'TS'
export interface Product {
id: string;
name: string;
priceMinor: number; // smallest currency unit: kobo, cents, pesewas
}
const products: Product[] = [
{ id: "tea", name: "Ginger tea", priceMinor: 150000 },
{ id: "rice", name: "Rice, 5 kg", priceMinor: 1250000 },
];
export function findProduct(id) {
return products.find((p) => p.id === id);
}
export function formatPrice(minor, currency) {
return `${currency} ${(minor / 100).toFixed(2)}`;
}
TSAn old JavaScript file nobody has converted, and the cart that uses both:
cat > src/discount.js <<'JS'
// Older code that nobody has converted yet.
export function applyDiscount(total, code) {
if (code === "WELCOME10") return Math.round(total * 0.9);
return total;
}
JS
cat > src/cart.ts <<'TS'
import { findProduct } from "./catalogue.js";
import { applyDiscount } from "./discount.js";
export interface CartLine {
productId: string;
quantity: number;
note?: string;
}
export function makeLine(productId: string, quantity: number, note?: string): CartLine {
return { productId, quantity, note };
}
export function lineTotal(line: CartLine): number {
const product = findProduct(line.productId);
return product.priceMinor * line.quantity;
}
export function cartTotal(lines: CartLine[], code?: string): number {
const subtotal = lines.reduce((sum, line) => sum + lineTotal(line), 0);
return applyDiscount(subtotal, code);
}
export function firstItemName(lines: CartLine[]): string {
return findProduct(lines[0].productId).name;
}
export function describeLines(lines: CartLine[]): string[] {
const out: string[] = [];
for (let i = 0; i < lines.length; i++) {
out.push(`${lines[i].quantity} x ${lines[i].productId}`);
}
return out;
}
TSA loader that returns any, an event hook for gift messages, and two notifiers:
cat > src/storage.ts <<'TS'
export function loadCart(json: string): any {
return JSON.parse(json);
}
TS
cat > src/events.ts <<'TS'
import type { CartLine } from "./cart.js";
export interface GiftLine extends CartLine {
giftMessage: string;
}
type LineListener = (line: CartLine) => void;
const listeners: LineListener[] = [];
export function onLineAdded(listener: LineListener): void {
listeners.push(listener);
}
export function addLine(lines: CartLine[], line: CartLine): void {
lines.push(line);
for (const listener of listeners) listener(line);
}
function printGiftMessage(line: GiftLine): void {
console.log(`Gift message: ${line.giftMessage.trim()}`);
}
onLineAdded(printGiftMessage);
TS
cat > src/notify.ts <<'TS'
export class Notifier {
send(to: string, message: string): string {
return `log for ${to}: ${message}`;
}
}
export class SmsNotifier extends Notifier {
send(to: string, message: string): string {
return `sms to ${to}: ${message.slice(0, 160)}`;
}
}
TSFinally the entry point, which exercises all of it:
cat > src/index.ts <<'TS'
import { cartTotal, describeLines, firstItemName, lineTotal, makeLine } from "./cart.js";
import { formatPrice } from "./catalogue.js";
import { addLine, type GiftLine } from "./events.js";
import { SmsNotifier } from "./notify.js";
import { loadCart } from "./storage.js";
const lines = loadCart('[{"productId":"tea","quantity":2}]');
const gift: GiftLine = { productId: "rice", quantity: 1, giftMessage: " Happy birthday, Ada " };
addLine(lines, gift);
console.log(describeLines(lines).join("; "));
console.log("First item:", firstItemName(lines));
const total = formatPrice(cartTotal(lines, "WELCOME10"), "NGN");
console.log(new SmsNotifier().send("+234 800 000 0000", `Your order total is ${total}`));
try {
console.log(lineTotal(makeLine("milk", 1)));
} catch (err) {
console.error("Could not price the line:", err.message);
}
TS
npm pkg set scripts.build="tsc" scripts.start="node dist/index.js" scripts.typecheck="tsc --noEmit"
npm run build
npm startCheck it worked
npx tsc --version prints Version 7.0.2. The build prints no errors, and the program prints five lines, ending with Could not price the line: Cannot read properties of undefined (reading 'priceMinor'). That last line is a bug the compiler could have caught: milk is not in the catalogue, findProduct returned undefined, and the code read a property from it anyway.
Step 2 · Count what each flag would add
You need a number before and after every change. This script runs tsc --noEmit with any extra flags you pass, and counts the errors by code. Flags given on the command line override tsconfig.json, so you can preview a flag without editing anything. Later steps use its --ratchet mode too:
cat > scripts/ts-errors.mjs <<'JS'
// Count TypeScript errors by code, optionally with extra compiler flags.
// node scripts/ts-errors.mjs [--someFlag ...] print the count
// node scripts/ts-errors.mjs --ratchet compare with ts-ratchet.json
// node scripts/ts-errors.mjs --ratchet --update lower the limit after a fix
import { spawnSync } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
const RATCHET_FILE = "ts-ratchet.json";
function countErrors(flags) {
const tsc = join(process.cwd(), "node_modules", "typescript", "bin", "tsc");
const run = spawnSync(process.execPath, [tsc, "--noEmit", "--pretty", "false", ...flags], {
encoding: "utf8",
});
if (run.error) throw run.error;
const byCode = new Map();
for (const match of `${run.stdout}${run.stderr}`.matchAll(/error (TS\d+):/g)) {
byCode.set(match[1], (byCode.get(match[1]) ?? 0) + 1);
}
let total = 0;
for (const n of byCode.values()) total += n;
return { total, byCode };
}
function report(label, { total, byCode }) {
const codes = [...byCode].sort((a, b) => b[1] - a[1]).map(([code, n]) => `${code} x${n}`);
const noun = total === 1 ? "error" : "errors";
console.log(`${label}: ${total} ${noun}${codes.length ? ` (${codes.join(", ")})` : ""}`);
}
const args = process.argv.slice(2);
if (args[0] !== "--ratchet") {
report(args.length ? `tsc ${args.join(" ")}` : "tsc", countErrors(args));
} else {
const ratchet = JSON.parse(readFileSync(RATCHET_FILE, "utf8"));
const result = countErrors(ratchet.flags);
report(`Target flags ${ratchet.flags.join(" ")}`, result);
if (result.total > ratchet.max) {
console.error(`Ratchet failed: ${result.total} errors, limit ${ratchet.max}. Fix the new errors.`);
process.exitCode = 1;
} else if (result.total < ratchet.max && args.includes("--update")) {
writeFileSync(RATCHET_FILE, `${JSON.stringify({ ...ratchet, max: result.total }, null, 2)}\n`);
console.log(`Limit lowered from ${ratchet.max} to ${result.total}.`);
} else if (result.total < ratchet.max) {
console.log(`Below the limit of ${ratchet.max}. Run with --update to lower it.`);
} else {
console.log(`At the limit of ${ratchet.max}.`);
}
}
JS
npm pkg set scripts.ts:errors="node scripts/ts-errors.mjs" scripts.ts:ratchet="node scripts/ts-errors.mjs --ratchet"The script counts error TS codes rather than lines, because one error can span several lines of explanation. Now survey the project:
npm run ts:errors
npm run ts:errors -- --noImplicitAny
npm run ts:errors -- --strictNullChecks
npm run ts:errors -- --strictFunctionTypes
npm run ts:errors -- --strict
npm run ts:errors -- --strict --noUncheckedIndexedAccess --exactOptionalPropertyTypes --noImplicitOverrideCheck it worked
Below npm's own header lines, the six runs report 0, 3, 2, 1, 7 and 12 errors. The 3 are all TS7006, a parameter that is implicitly any. The last line is the full target. On a real codebase, run the same survey and start with the flag whose count is smallest, or whose errors sit in the code you change most often. This tutorial goes in the order most teams use, because each flag makes the next one's errors more accurate.
Step 3 · Set a ratchet before you fix anything
A ratchet is a number that may only go down. Write the target flags and today's count to a file you commit:
cat > ts-ratchet.json <<'JSON'
{
"flags": ["--strict", "--noUncheckedIndexedAccess", "--exactOptionalPropertyTypes", "--noImplicitOverride"],
"max": 12
}
JSON
npm run ts:ratchetIn CI, run these two commands after npm ci, as two steps of whatever pipeline you use (for example, two run: lines in a GitHub Actions job):
npm run typecheck
npm run ts:ratchettypecheck keeps the flags already in tsconfig.json at zero errors. ts:ratchet checks the flags you have not reached yet, and fails when the count rises above the limit. Only people lower the limit, by running --update after a fix and committing the new file. CI never runs --update.
See it catch something. Add a new file with an untyped parameter, the kind of code that keeps arriving while you clean up:
cat > src/report.ts <<'TS'
export function summarise(order) {
return `${order.lines.length} lines`;
}
TS
npm run typecheck
npm run ts:ratchet || echo "ratchet exited with status $?"
rm src/report.tsCheck it worked
The first ratchet run prints ... 12 errors ... and At the limit of 12. With report.ts added, typecheck still passes, because the loose tsconfig.json allows the untyped parameter, but the ratchet prints Ratchet failed: 13 errors, limit 12. and ratchet exited with status 1. That is the job of the ratchet: the backlog can shrink, but cannot grow behind your back.
A total count has one weakness: someone can fix one error and add another, and the number stays the same. If that worries you, extend the script to keep a count per file, and fail when any file goes up.
Step 4 · Turn on noImplicitAny
noImplicitAny reports every place the compiler had to guess any because nothing said what the type was. See the errors themselves:
npx tsc --noEmit --noImplicitAny || echo "tsc exited with status $?"All three are in catalogue.ts: id, minor and currency. The fix is the type the function was always meant to take. Write the return types too, so a later change inside the body cannot quietly change what callers get:
cat > src/catalogue.ts <<'TS'
export interface Product {
id: string;
name: string;
priceMinor: number; // smallest currency unit: kobo, cents, pesewas
}
const products: Product[] = [
{ id: "tea", name: "Ginger tea", priceMinor: 150000 },
{ id: "rice", name: "Rice, 5 kg", priceMinor: 1250000 },
];
export function findProduct(id: string): Product | undefined {
return products.find((p) => p.id === id);
}
export function formatPrice(minor: number, currency: string): string {
return `${currency} ${(minor / 100).toFixed(2)}`;
}
TSThe any nobody guessed
noImplicitAny does not report an any that someone wrote, and it does not check .js files at all. Find the written ones:
grep -rnw "any" src || echo "no explicit any left"It finds loadCart. Its result comes from JSON.parse, so it can be anything, and any lets every caller assume whatever it likes. Return unknown from the parse, check the shape at runtime, and only then call it a CartLine[]. This matters most for data you do not control, such as a cart saved on a phone and sent back after a dropped connection:
cat > src/storage.ts <<'TS'
import type { CartLine } from "./cart.js";
function isCartLine(value: unknown): value is CartLine {
return (
typeof value === "object" &&
value !== null &&
"productId" in value &&
typeof value.productId === "string" &&
"quantity" in value &&
typeof value.quantity === "number" &&
(!("note" in value) || typeof value.note === "string")
);
}
export function loadCart(json: string): CartLine[] {
const data: unknown = JSON.parse(json);
if (!Array.isArray(data) || !data.every(isCartLine)) {
throw new Error("Saved cart is not a list of cart lines");
}
return data;
}
TSThen convert the JavaScript file. Its parameters were any too, and every caller inherited that:
rm src/discount.js
cat > src/discount.ts <<'TS'
export function applyDiscount(total: number, code?: string): number {
if (code === "WELCOME10") return Math.round(total * 0.9);
return total;
}
TSThe import in cart.ts already says ./discount.js, which is the compiled name, so it does not change. In a project with many .js files, "checkJs": true type-checks them in place, using JSDoc comments for types, before you convert them.
Now make the flag permanent and lower the ratchet:
cat > tsconfig.json <<'JSON'
{
"compilerOptions": {
"target": "es2023",
"module": "nodenext",
"rootDir": "src",
"outDir": "dist",
"strict": false,
"noImplicitAny": true,
"allowJs": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}
JSON
npm run typecheck
npm run ts:ratchet -- --updateCheck it worked
grep lists src/storage.ts:1:export function loadCart(json: string): any { before the fix. typecheck passes with noImplicitAny in tsconfig.json, and the ratchet prints Limit lowered from 12 to 9. Open ts-ratchet.json and you see "max": 9. A flag set on its own wins over strict, so this line stays in force whatever strict says.
Step 5 · Turn on strictNullChecks
Without strictNullChecks, null and undefined fit into every type, so findProduct returning Product | undefined meant nothing. With it, the compiler makes you deal with the missing case:
npm run ts:errors -- --strictNullChecks
npx tsc --noEmit --strictNullChecks || echo "tsc exited with status $?"Both errors are in cart.ts: lineTotal reads product.priceMinor when product may be undefined, which is the milk crash from the first step, and firstItemName reads .name from a lookup that may find nothing. The tempting fix is product!.priceMinor, which silences the compiler and keeps the crash. Decide what each function should do instead. An unknown product in a cart is a real error, so lineTotal throws one with a useful message. A cart with no known first item has no name, so firstItemName says so in its return type:
cat > src/cart.ts <<'TS'
import { findProduct } from "./catalogue.js";
import { applyDiscount } from "./discount.js";
export interface CartLine {
productId: string;
quantity: number;
note?: string;
}
export function makeLine(productId: string, quantity: number, note?: string): CartLine {
return { productId, quantity, note };
}
export function lineTotal(line: CartLine): number {
const product = findProduct(line.productId);
if (product === undefined) {
throw new Error(`Unknown product: ${line.productId}`);
}
return product.priceMinor * line.quantity;
}
export function cartTotal(lines: CartLine[], code?: string): number {
const subtotal = lines.reduce((sum, line) => sum + lineTotal(line), 0);
return applyDiscount(subtotal, code);
}
export function firstItemName(lines: CartLine[]): string | undefined {
return findProduct(lines[0].productId)?.name;
}
export function describeLines(lines: CartLine[]): string[] {
const out: string[] = [];
for (let i = 0; i < lines.length; i++) {
out.push(`${lines[i].quantity} x ${lines[i].productId}`);
}
return out;
}
TS
cat > tsconfig.json <<'JSON'
{
"compilerOptions": {
"target": "es2023",
"module": "nodenext",
"rootDir": "src",
"outDir": "dist",
"strict": false,
"noImplicitAny": true,
"strictNullChecks": true,
"allowJs": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}
JSON
npm run typecheck
npm run ts:ratchet -- --updateCheck it worked
The preview reports 2 errors, one TS18048 ('product' is possibly 'undefined') and one TS2532 (Object is possibly 'undefined'). After the fix, typecheck passes and the ratchet prints Limit lowered from 9 to 7. The change of return type rippled out to callers: had any of them used the name as a definite string, the compiler would now point at it, which is the point of the flag. On a large codebase this flag usually has the biggest count, so expect to land it over several pull requests with the ratchet holding the line between them.
Step 6 · Turn on strictFunctionTypes
This one catches a bug that runs fine until the wrong data arrives. onLineAdded promises to call each listener with any CartLine. printGiftMessage only works with a GiftLine, which has a giftMessage. Without the flag, TypeScript accepts it anyway:
npx tsc --noEmit --strictFunctionTypes || echo "tsc exited with status $?"The first time a normal line is added, line.giftMessage.trim() throws. The fix is not a cast. Register a listener that accepts every CartLine, and check inside it with a type guard, a function whose line is GiftLine return type tells the compiler what a true result proves:
cat > src/events.ts <<'TS'
import type { CartLine } from "./cart.js";
export interface GiftLine extends CartLine {
giftMessage: string;
}
type LineListener = (line: CartLine) => void;
const listeners: LineListener[] = [];
export function onLineAdded(listener: LineListener): void {
listeners.push(listener);
}
export function addLine(lines: CartLine[], line: CartLine): void {
lines.push(line);
for (const listener of listeners) listener(line);
}
function isGiftLine(line: CartLine): line is GiftLine {
return "giftMessage" in line && typeof line.giftMessage === "string";
}
function printGiftMessage(line: GiftLine): void {
console.log(`Gift message: ${line.giftMessage.trim()}`);
}
onLineAdded((line) => {
if (isGiftLine(line)) printGiftMessage(line);
});
TS
cat > tsconfig.json <<'JSON'
{
"compilerOptions": {
"target": "es2023",
"module": "nodenext",
"rootDir": "src",
"outDir": "dist",
"strict": false,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"allowJs": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}
JSON
npm run typecheck
npm run ts:ratchet -- --updateCheck it worked
The preview prints a TS2345 error saying the (line: GiftLine) => void argument is not assignable to LineListener, because giftMessage is missing in CartLine. After the fix, typecheck passes and the ratchet prints Limit lowered from 7 to 6. One limit to know: the check applies to function types such as LineListener, not to methods written with method syntax (listen(line: CartLine): void inside an interface), whose parameters stay loosely checked.
Step 7 · Switch to strict
strict is a family. Besides the three flags you have, it includes checks such as strictPropertyInitialization, strictBindCallApply, noImplicitThis and useUnknownInCatchVariables, and TypeScript 7 no longer lets you turn alwaysStrict off. Preview the rest of the family:
npm run ts:errors -- --strict
npx tsc --noEmit --strict || echo "tsc exited with status $?"One error is left, from useUnknownInCatchVariables: in index.ts, err in the catch block is unknown, because JavaScript can throw anything, not only an Error. Check before you read .message:
cat > src/index.ts <<'TS'
import { cartTotal, describeLines, firstItemName, lineTotal, makeLine } from "./cart.js";
import { formatPrice } from "./catalogue.js";
import { addLine, type GiftLine } from "./events.js";
import { SmsNotifier } from "./notify.js";
import { loadCart } from "./storage.js";
const lines = loadCart('[{"productId":"tea","quantity":2}]');
const gift: GiftLine = { productId: "rice", quantity: 1, giftMessage: " Happy birthday, Ada " };
addLine(lines, gift);
console.log(describeLines(lines).join("; "));
console.log("First item:", firstItemName(lines));
const total = formatPrice(cartTotal(lines, "WELCOME10"), "NGN");
console.log(new SmsNotifier().send("+234 800 000 0000", `Your order total is ${total}`));
try {
console.log(lineTotal(makeLine("milk", 1)));
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error("Could not price the line:", message);
}
TSReplace the three single flags with "strict": true. Keeping them as well would do no harm, but a future reader would wonder which one wins:
cat > tsconfig.json <<'JSON'
{
"compilerOptions": {
"target": "es2023",
"module": "nodenext",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"allowJs": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}
JSON
npm run typecheck
npm run ts:ratchet -- --updateCheck it worked
The preview reports 1 error, TS18046: 'err' is of type 'unknown'. After the fix, typecheck passes with "strict": true, and the ratchet prints Limit lowered from 6 to 5. The project is now where the setup tutorial starts. The remaining 5 belong to checks strict leaves out.
Step 8 · Add noUncheckedIndexedAccess and exactOptionalPropertyTypes
These two are not part of strict, because they report code that is often fine, and many teams still find them worth it. Preview each:
npm run ts:errors -- --noUncheckedIndexedAccess
npm run ts:errors -- --exactOptionalPropertyTypes
npx tsc --noEmit --noUncheckedIndexedAccess --exactOptionalPropertyTypes || echo "tsc exited with status $?"noUncheckedIndexedAccess makes lines[0] and lines[i] possibly undefined, which they are when the array is empty or the index is wrong. firstItemName really does need the check: an empty cart has no first line. In describeLines, the index was never needed. map visits each line that exists, so the question goes away rather than being answered with !.
exactOptionalPropertyTypes separates "no note property" from "a note property set to undefined". makeLine always wrote the key, even with no note. The two look the same when you read line.note, but not to "note" in line, Object.keys or a spread over another object, where an explicit undefined overwrites a value. Leave the key out when there is no note:
cat > src/cart.ts <<'TS'
import { findProduct } from "./catalogue.js";
import { applyDiscount } from "./discount.js";
export interface CartLine {
productId: string;
quantity: number;
note?: string;
}
export function makeLine(productId: string, quantity: number, note?: string): CartLine {
return note === undefined ? { productId, quantity } : { productId, quantity, note };
}
export function lineTotal(line: CartLine): number {
const product = findProduct(line.productId);
if (product === undefined) {
throw new Error(`Unknown product: ${line.productId}`);
}
return product.priceMinor * line.quantity;
}
export function cartTotal(lines: CartLine[], code?: string): number {
const subtotal = lines.reduce((sum, line) => sum + lineTotal(line), 0);
return applyDiscount(subtotal, code);
}
export function firstItemName(lines: CartLine[]): string | undefined {
const first = lines[0];
if (first === undefined) return undefined;
return findProduct(first.productId)?.name;
}
export function describeLines(lines: CartLine[]): string[] {
return lines.map((line) => `${line.quantity} x ${line.productId}`);
}
TS
cat > tsconfig.json <<'JSON'
{
"compilerOptions": {
"target": "es2023",
"module": "nodenext",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"allowJs": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}
JSON
npm run typecheck
npm run ts:ratchet -- --updateCheck it worked
Before the fix the previews report 3 errors (all TS2532) and 1 error (TS2375, which names exactOptionalPropertyTypes in its message). After it, typecheck passes and the ratchet prints Limit lowered from 5 to 1. If a property should be allowed to hold undefined on purpose, say so in the type, note?: string | undefined, rather than switching the flag off.
Step 9 · Add noImplicitOverride and finish
noImplicitOverride asks for the override keyword on any method that replaces one from a parent class:
npx tsc --noEmit --noImplicitOverride || echo "tsc exited with status $?"The keyword is a promise the compiler checks. If someone later renames Notifier.send to deliver, SmsNotifier.send stops overriding anything and becomes a stray method that nothing calls. With override in place, that rename is a compile error instead of a silent change in behaviour:
cat > src/notify.ts <<'TS'
export class Notifier {
send(to: string, message: string): string {
return `log for ${to}: ${message}`;
}
}
export class SmsNotifier extends Notifier {
override send(to: string, message: string): string {
return `sms to ${to}: ${message.slice(0, 160)}`;
}
}
TS
cat > tsconfig.json <<'JSON'
{
"compilerOptions": {
"target": "es2023",
"module": "nodenext",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"allowJs": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}
JSON
npm run typecheck
npm run ts:ratchet -- --update
npm run build
npm startA note on the SMS limit: 160 characters holds only for text in the GSM 7-bit alphabet. A message with characters outside it, such as the dotted letters in Yoruba or Igbo names, is sent in UCS-2, where one message holds 70 characters. If your customers write in those languages, that limit belongs in a function with a test, not in a literal.
Check it worked
The preview error is TS4114: This member must have an 'override' modifier because it overrides a member in the base class 'Notifier'. After the fix the ratchet prints Limit lowered from 1 to 0., and the program prints the same first four lines as at the start, then Could not price the line: Unknown product: milk in place of the old crash message. With every target flag now in tsconfig.json, npm run typecheck guards them all. Delete ts-ratchet.json and the CI step, or put the next flag you want in flags and start again.
Remove the demo when you are done:
cd ~
rm -rf ~/ts-tighten-demoNext steps
- Use the stricter types to model data whose shape changes: narrow types safely with discriminated unions.
- Replace copy-pasted helpers with typed ones: write reusable TypeScript with generics.
- Start the next project strict from day one: set up a TypeScript 7 project.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials