The user wants a "TypeScript strictness ratchet". This implies a guide or a process for gradually increasing the strictness of a TypeScript codebase. The request asks for "flags, refactors, and safety metrics".
1. Understand the Goal:
* Goal: Migrate a loose TypeScript codebase to a strict one incrementally.
* Key Elements:
* Flags: The tsconfig.json compiler options that enforce strictness.
* Refactors: Code changes required to satisfy the new flags.
* Safety Metrics: Ways to measure the improvement (e.g., reduced any usage, specific error counts).
2. Determine the Structure:
* A "ratchet" implies steps or levels. I should organize the response in levels of increasing strictness.
* Level 1: The Basics (Baseline).
* Level 2: Intermediate (Common sources of bugs).
* Level 3: Advanced (Strict nulls and checks).
* Level 4: Expert (Maximum strictness).
3. Drafting the Content - Level by Level:
* **Level 1: The Cleanup (Low Hanging Fruit)**
* *Flags:* `noUnusedLocals`, `noUnusedParameters`. These are annoying but easy.
* *Refactor:* Delete commented-out code, remove unused imports.
* *Metric:* Count of unused variables.
* **Level 2: Implicit Any (The Safety Net)**
* *Flags:* `noImplicitAny`. This is the big one.
* *Refactor:* Typing function arguments, maybe explicit `any` temporarily (with `// @ts-expect-error` or a todo list).
* *Metric:* Count of `any` keywords (regex search).
* **Level 3: Null Safety (The Billion Dollar Mistake)**
* *Flags:* `strictNullChecks`. This is often the hardest refactor.
* *Refactor:* Handling `undefined`/`null` explicitly, using optional chaining `?.`, nullish coalescing `??`.
* *Metric:* Number of "Object is possibly 'null' or 'undefined'" errors resolved.
* **Level 4: Strict Mode & Advanced Checks**
* *Flags:* `strict: true` (the master switch), `strictFunctionTypes`, `strictBindCallApply`, `noImplicitThis`, `alwaysStrict`.
* *Refactor:* Fixing `this` context issues, fixing bind/call usage.
* *Metric:* Code coverage stability, reduced runtime errors.
* **Level 5: Extreme Strictness (Code Review/Quality)**
* *Flags:* `noImplicitReturns`, `noFallthroughCasesInSwitch`, `noUncheckedIndexedAccess`.
* *Refactor:* Adding explicit returns, handling array access safely (checking for undefined).
* *Metric:* Cyclomatic complexity (maybe?), explicit return coverage.
4. Refining the "Ratchet" Mechanism:
* How do you actually do this?
* It's not just "flip the switch". It's "add the flag to tsconfig, fix errors, commit".
* Need to mention CI integration. If CI fails, the build fails.
5. Developing the "Safety Metrics" aspect:
* The user specifically asked for this. I need a script or a way to quantify strictness.
* Idea: A script that counts any, checks tsconfig, and outputs a "Strictness Score".
* Idea: type-coverage package is a standard tool for this.
6. Structuring the Output:
* Introduction: Philosophy of the ratchet (never go back).
* Phase 1: Hygiene: Unused code.
* Phase 2: Types: Implicit Any.
* Phase 3: Nulls: The big hurdle.
* Phase 4: The Master Switch: strict: true.
* Phase 5: Exhaustiveness: Edge cases.
* Tools/Metrics: How to measure.
7. Review against "TypeScript" nuances:
* Make sure to explain why a flag is added.
* Mention // @ts-expect-error as a temporary escape hatch.
* Mention the type-coverage library as it fits "metrics" perfectly.
8. Self-Correction/Polishing during drafting:
* Initial thought: Just list flags.
* Correction: The user asked for refactors too. I need to show code examples of what breaks and how to fix it.
* Initial thought: Dump everything at once.
* Correction: It's a "ratchet". Needs to be gradual. Present as a step-by-step plan.
9. Final Polish:
* Use formatting (code blocks, bold text) to make it readable.
* Create a concrete tsconfig.json evolution.
* Add a summary table.
(Self-Correction during output generation): I will structure this as a "Migration Plan" with specific phases. I'll define the Flag, the typical Refactor required, and the Metric to track for each phase.
Phase 1: The Basics (Hygiene)
Phase 2: The Wall (Implicit Any)
Phase 3: The Cliff (Null Safety)
Phase 4: The Summit (Strictness & Logic)
Phase 5: The Fortress (Edge Cases)
Metrics Section: Provide a script using type-coverage.
This looks like a solid plan. I will generate the response based on this structure.
This guide outlines a step-by-step "ratchet" strategy to tighten TypeScript security. The goal is to increase strictness incrementally without breaking the build, allowing your team to adapt refactors gradually.
We progress from simple hygiene to complex type safety, defining the Flag, the Refactor Strategy, and the Safety Metric for each level.
Phase 1: Hygiene & Explicitness
Goal: Clean up unused code and force explicit typing to improve readability.
Level 1: The Cleanse
Flags:
{
"noUnusedLocals": true,
"noUnusedParameters": true
}
The Refactor:
- Run the linter/compiler.
- Identify unused imports and variables.
- Action: Prefix intentionally unused variables (e.g., in callbacks) with
_ (e.g., _req, _res) or remove them entirely.
Safety Metric:
- Dead Code Index: Count of unused variables dropped to
0.
Level 2: The "Any" Wall
Flags:
{
"noImplicitAny": true
}
The Refactor:
This is often the most difficult step.
- Isolate: If a module is complex, temporarily cast to
any explicitly: (myData as any).property to silence the error locally.
- Define: Create Interfaces/Types for data shapes.
- Replace: Swap
any with the defined types.
Safety Metric:
- Explicit
any Count: Use a script to count occurrences of : any. Aim to reduce this number every sprint.
Phase 2: Nullability & Binding
Goal: Handle "undefined" and "null" correctly and ensure this context is predictable.
Level 3: The Billion Dollar Mistake
Flags:
{
"strictNullChecks": true
}
The Refactor:
- Trace: The compiler will complain that
object might be null.
- Guard: Add type guards.
- Before:
user.profile.name
- After:
user?.profile?.name (Optional Chaining) or if (!user) return;
- Simplify: Use the Nullish Coalescing operator (
??) for defaults.
Safety Metric:
- Runtime Crash Risk: Theoretical reduction in "Cannot read property of undefined" errors.
Level 4: Context Binding
Flags:
{
"noImplicitThis": true,
"strictBindCallApply": true
}
The Refactor:
- Class Methods: If passing methods as callbacks (e.g.,
onClick={this.handleClick}), bind them in the constructor or use arrow functions handleClick = () => { ... }.
- Call/Apply: Ensure arguments passed to
call() or apply() match the function signature.
Safety Metric:
this Instability: Count of explicit bind calls (aim to reduce by using arrow functions).
Phase 3: The "Strict" Master Switch
Goal: Enable the umbrella flag and handle complex inference.
Level 5: The Standard
Flags:
{
"strict": true
}
Note: This enables strictNullChecks, noImplicitAny, strictFunctionTypes, strictPropertyInitialization, etc., if not already on.
The Refactor:
- Property Initialization: Classes will error if properties aren't assigned in the constructor.
- Fix: Use the "definite assignment assertion"
name!: string if initialized externally, or declare as name: string | undefined.
- Function Argument Bivariance:
strictFunctionTypes ensures function arguments are checked contravariantly.
- Fix: Ensure callback types match exactly.
Safety Metric:
- Type Coverage Percentage: Percentage of code covered by non-
any types (measured by type-coverage package).
Phase 4: Exhaustiveness & Edge Cases
Goal: Eliminate logic errors and unhandled states.
Level 6: Switch Safety
Flags:
{
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
}
The Refactor:
- Returns: Ensure all code paths in a function return a value (or explicitly return
void).
- Switches: Remove
break omissions in switch statements.
- Exhaustiveness: Add a
default case or a never check to ensure all enum cases are handled.
// The "Never" pattern
function getArea(shape: Shape) {
switch (shape.kind) {
case 'square': return shape.size ** 2;
case 'circle': return Math.PI * shape.radius ** 2;
default:
const _exhaustiveCheck: never = shape; // Error if a new shape is added
return _exhaustiveCheck;
}
}
Safety Metric:
- Unhandled State Risk: Number of
switch statements lacking default logic.
Phase 5: Fortress Mode (High Security)
Goal: Maximum safety, often used in financial or critical infrastructure code.
Level 7: No Excuses
Flags:
{
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
}
The Refactor:
- Arrays:
const item = array[0] now returns T | undefined. You must check existence before use.
- Optionals:
interface Props { name?: string } allows undefined but not null. exactOptionalPropertyTypes enforces strict differentiation between undefined and "missing".
Safety Metric:
- Index Safety Score: 100% of array access guarded by existence checks.
Metric Tracker Dashboard
To visualize your progress, run this simple script to track your "Type Safety Score" (TSS).
strictness-report.js
// Prerequisite: npm install type-coverage
// Usage: node strictness-report.js
const { coverage } = require('type-coverage');
const fs = require('fs');
async function generateReport() {
const { percent, totalCount, correctCount } = await coverage('.', { strict: true });
const anyCount = totalCount - correctCount;
console.log('--- TypeScript Strictness Ratchet Report ---');
console.log(`Safety Score: ${percent.toFixed(2)}%`);
console.log(`Remaining \`any\`: ${anyCount}`);
// Read tsconfig to check flags (simplified)
const config = JSON.parse(fs.readFileSync('./tsconfig.json', 'utf8'));
const strictFlags = Object.keys(config.compilerOptions).filter(k => k.includes('strict') || k.includes('noImp'));
console.log(`Active Strict Flags: ${strictFlags.length}`);
// Fail CI if score drops below threshold
if (percent < 95.00) {
console.error("Metric Fail: Type coverage is below 95%");
process.exit(1);
}
}
generateReport();
Implementation Strategy (The Ratchet)
- Pick a level from above.
- Enable the flag in
tsconfig.json.
- Run
tsc. If errors exist, suppress them only using // @ts-expect-error comments with a "TODO: Fix Type" note.
- Add the Strictness Report to your CI pipeline.
- Ratchet Down: Every week, aim to remove 10
// @ts-expect-error comments or reduce the "Any Count" by 5%.