We are going to create a plan for gradually enabling TypeScript strict flags and refactoring for safety.
The idea is to start with a base (maybe strict: false or minimal strictness) and then gradually turn on flags, fixing errors as we go.
We'll also consider code metrics (like cyclomatic complexity, code coverage) but focus on TypeScript's strictness first.
Steps:
- Start with the current state (maybe non-strict or partially strict).
- Enable one flag at a time (or a small set if they are tightly coupled) and fix the errors.
- Use a "ratchet" approach: once a flag is enabled and the code compiles, we don't turn it off again.
- Consider using
// @ts-expect-error or // @ts-ignore sparingly and only for known issues that we plan to fix later.
- For each flag, we might need to refactor code to satisfy the new constraint.
We'll list the strict flags in an order that makes sense (from less invasive to more invasive).
Common strict flags (in order of increasing strictness):
a. noImplicitAny - Disallow implicit any type.
b. strictNullChecks - Enable strict null checking.
c. strictFunctionTypes - Enable stricter checking for function types.
d. strictBindCallApply - Enable stricter checking for bind, call, and apply.
e. strictPropertyInitialization - Check that class properties are initialized in the constructor.
f. noImplicitThis - Raise error on this expressions with an implied any type.
g. alwaysStrict - Parse in strict mode and emit "use strict" for each file.
h. noImplicitReturns - Report error when not all code paths in function return a value.
i. noFallthroughCasesInSwitch - Report errors for fallthrough cases in switch statements.
We might also consider:
noUnusedLocals and noUnusedParameters (but these might be too noisy at the beginning, so maybe later)
noImplicitOverride (if using inheritance a lot)
However, note that the strict flag in TypeScript enables all of the above (except some like noUnusedLocals and noUnusedParameters).
But we want to do it gradually, so we'll enable them one by one.
How to proceed:
-
Check current tsconfig.json. If strict is already true, then we are done with the strict flags? Not necessarily, because there are other checks we might want to enable.
But if we are starting from non-strict, we can set strict: false and then add the flags individually.
-
Alternatively, we can start by setting strict: true and then fix all the errors? That might be too big of a change at once.
-
The gradual approach:
Step 1: Enable noImplicitAny
Step 2: Enable strictNullChecks
Step 3: Enable strictFunctionTypes
Step 4: Enable strictBindCallApply
Step 5: Enable strictPropertyInitialization
Step 6: Enable noImplicitThis
Step 7: Enable alwaysStrict (but note that if we are using ES6 modules, this might be redundant because strict mode is the default for ES6 modules)
Step 8: Enable noImplicitReturns
Step 9: Enable noFallthroughCasesInSwitch
-
After that, we can consider noUnusedLocals and noUnusedParameters (but these might require a lot of changes, so maybe after the others).
-
We might also want to set noImplicitOverride if we have a lot of inheritance.
-
We can also consider setting useUnknownInCatchVariables (if using TypeScript 4.0+) and exactOptionalPropertyTypes (if using TypeScript 4.4+).
However, the order might vary depending on the codebase.
But note: some flags depend on others. For example, strictNullChecks might make noImplicitAny errors appear in places where any was used because of null or undefined.
So we might need to adjust the order.
A common order that works for many projects:
-
noImplicitAny (but without strictNullChecks we might miss some any due to null/undefined? Actually, noImplicitAny will catch implicit any even without strict null checks. However, with strict null checks, more places might get an implicit any because null and undefined are distinct.)
-
strictNullChecks (this is a big one and might require a lot of changes, so we do it after noImplicitAny? Or before? Let's think:)
Actually, the TypeScript team recommends enabling `strictNullChecks` first because it can reveal more `any` issues? But note: without `noImplicitAny`, you might have `any` that are not caught until you enable `noImplicitAny`.
But if we enable `strictNullChecks` first, we might see errors about `null` and `undefined` that were previously ignored. Then when we enable `noImplicitAny`, we might see even more.
However, the typical recommendation is to enable `strict` (which includes all) and then fix. But we are doing gradual.
I think a safe order is:
a. `noImplicitAny` (so we don't have implicit `any` even without strict null checks)
b. `strictNullChecks` (then we have to handle `null` and `undefined` explicitly, and we already have no implicit `any` so we won't get new implicit `any` from `null`/`undefined`? Actually, we might: if we have a variable that can be `null` or `undefined` and we don't specify, then with `strictNullChecks` it becomes `any`? No, it becomes `any` only if we don't have a type and we are assigning `null` or `undefined`? Actually, without `noImplicitAny`, if we have:
let x;
x = null;
then without `strictNullChecks`, `x` is `any` and we can assign `null`. With `strictNullChecks` and without `noImplicitAny`, `x` becomes `any`? Actually, no: without `noImplicitAny`, `x` is `any` and with `strictNullChecks`, `any` can be assigned `null` because `any` can be assigned anything. So we don't get an error until we enable `noImplicitAny` and then `x` becomes implicitly `any` (because we declared it without a type and without an initializer) and then `noImplicitAny` will error.
So the order might not matter for this case? Actually, we get the same error when both are enabled.
Let's try to break it down:
- If we enable `strictNullChecks` without `noImplicitAny`:
let x; // x: any
x = null; // allowed because any can be assigned null.
So no error.
- If we enable `noImplicitAny` without `strictNullChecks`:
let x; // error: implicit any.
So we have to give a type.
- If we enable both:
let x; // error: implicit any (because without initializer and without type, it's any). But note: with `strictNullChecks` and `noImplicitAny`, the error is still about implicit any.
So actually, `noImplicitAny` will catch the declaration without type regardless of `strictNullChecks`.
But note: with `strictNullChecks` and without `noImplicitAny`, we might have:
let x = null; // x: any (because null is assignable to any, and without type annotation, it's any)
Then `noImplicitAny` will catch that.
So I think we can do:
Step 1: `noImplicitAny` (catch all implicit any, even those that are because of `null` or `undefined` assignments? Actually, if we assign `null` to a variable without a type, it's still `any` and then caught by `noImplicitAny`.)
Step 2: `strictNullChecks` (then we have to adjust the code to handle `null` and `undefined` explicitly, and we already have types for most things because of `noImplicitAny`)
But wait: what about a function parameter without a type? With `noImplicitAny` we have to give it a type, and then with `strictNullChecks` we have to consider if it can be `null` or `undefined`.
So I think:
Enable `noImplicitAny` first, so we have to put types everywhere. Then when we enable `strictNullChecks`, we have to adjust those types to include or exclude `null` and `undefined` as appropriate.
This seems logical.
7. Then the rest of the flags are less pervasive.
Proposed order:
noImplicitAny
strictNullChecks
strictFunctionTypes
strictBindCallApply
strictPropertyInitialization
noImplicitThis
alwaysStrict (if necessary, because ES6 modules are strict by default)
noImplicitReturns
noFallthroughCasesInSwitch
Then, if we want:
noUnusedLocals
noUnusedParameters
And then:
noImplicitOverride (if using inheritance)
But note: noUnusedLocals and noUnusedParameters might be very noisy and might require a lot of changes (like removing code that is used in templates or via string references in frameworks). So we might do them last.
Also, we might want to set exactOptionalPropertyTypes (TypeScript 4.4+) and useUnknownInCatchVariables (TypeScript 4.0+).
However, the exact order might depend on the project.
Implementation:
We'll create a script (or a series of steps) that:
- Reads the current
tsconfig.json.
- For each flag in the desired order (that is not already enabled):
a. Add the flag to
compilerOptions (if not present) and set it to true.
b. Run tsc (or the build) and note the errors.
c. Fix the errors in the code (or add // @ts-expect-error for known issues that we will fix later, but this should be minimal).
d. Commit the changes (so we have a history of each step).
We can do this manually or write a script.
But note: we might have to fix errors in a specific order because some errors might be caused by the combination of flags.
Alternatively, we can enable all the flags at once and then fix, but that might be overwhelming.
The gradual approach is better for large codebases.
However, note that some flags might interact and cause more errors when enabled together. But we are fixing after each step, so it should be okay.
Another idea: we can enable the flags in the order above and after each step, we run the tests (if any) to make sure we didn't break functionality.
But note: the type errors are compile-time only, so we might not have tests for all type errors. But we should have tests for the runtime behavior.
So:
For each flag:
- Enable the flag.
- Fix all type errors (or mark with `// @ts-expect-error` if necessary and create a ticket to fix).
- Run tests to ensure no runtime breakage (because the type fixes might change behavior? Actually, type fixes are usually just adding types or adjusting to be more correct, but sometimes we might change the code to satisfy the type checker and that could change behavior. So tests are important.)
We can also set up a CI that runs tsc with the current set of flags and fails on type errors.
But we want to gradually enable, so we might have a branch for each step.
Alternatively, we can do:
- Have a `tsconfig.strict.json` that has all the strict flags we want.
- Then, in our CI, we run `tsc --project tsconfig.strict.json` and fail on errors.
- Then, we gradually enable the flags in the main `tsconfig.json` and fix the errors in the main branch.
But we want to do it flag by flag.
Let me think about a practical approach:
We can have a script that:
currentFlags = read tsconfig.json
for flag in desiredOrder:
if currentFlags[flag] is not true:
set currentFlags[flag] = true
write tsconfig.json
run tsc and capture errors
fix errors (manually or with some automated fixes where possible)
commit
But we don't want to automate the fixing because it's code and might require human judgment.
So we can do:
Step 0: Ensure we have a good test suite and that the current code compiles with the current tsconfig.
Step 1: Pick the first flag from the order that is not enabled.
Step 2: Enable that flag in `tsconfig.json`.
Step 3: Run `tsc` and list all errors.
Step 4: Fix the errors (one by one, or in batches, but fix them).
Step 5: Run tests to ensure no breakage.
Step 6: Commit.
Step 7: Repeat for the next flag.
We can also use tools like ts-migrate (from Airbnb) which does something similar for migrating to TypeScript, but we are already in TypeScript.
Alternatively, we can use the --noEmit flag to check for errors without emitting.
But note: some errors might be in dependencies? No, we are only checking our code.
Also, we might have to fix third-party declaration files? If we are using skipLibCheck we might not see errors in node_modules. But if we want to be strict about third-party, we might have to fix or report issues.
However, for our own code, we want to fix.
Let's write a plan:
Phase 1: Preparation
- Ensure `tsconfig.json` has `"noEmit": true`? Not necessary, but we can use `tsc --noEmit` to only check.
- Make sure we have a way to run `tsc` with the current `tsconfig.json`.
- Have a good test suite.
Phase 2: Gradual enablement
For each flag in the order:
1. Enable the flag in `tsconfig.json`.
2. Run `tsc --noEmit` and note the number of errors.
3. Fix the errors in the code. For each error, decide:
- Can we fix by adding a type? (most common)
- Do we need to refactor the code to be more type-safe?
- Is it a false positive? (rare, but possible)
- If we cannot fix immediately, we can use `// @ts-expect-error` but only with a comment explaining why and a ticket to fix.
4. After fixing, run `tsc --noEmit` again to ensure no errors.
5. Run tests.
6. Commit.
Phase 3: After all flags
- Consider enabling `noUnusedLocals` and `noUnusedParameters` (if not already in the strict set).
- Consider setting `exactOptionalPropertyTypes` and `useUnknownInCatchVariables` if using appropriate TypeScript version.
- Consider setting `noImplicitOverride` if using inheritance.
But note: the strict flag does not include noUnusedLocals and noUnusedParameters.
So we might have to add them separately.
Also, we might want to set noUnusedLocals and noUnusedParameters to true at the end.
However, these can be very noisy and might require removing code that is used by frameworks (like Angular templates, Vue templates, etc.) or by string-based access (like obj["someProp"]). So we might need to use /* @ts-ignore */ or // @ts-expect-error in those cases, but then we lose the check for that line.
Alternatively, we can configure the linter (ESLint) to catch unused code, but TypeScript's checks are more accurate because it knows the types.
So we might want to enable them and then fix by removing unused code or using the variables.
But if we are using a framework that uses string-based property access, we might have to keep the property and use it in a way that TypeScript can see? Or we can use /* @ts-ignore */ for that specific line? But then we are ignoring the error.
Alternatively, we can use // @ts-expect-error for the variable if it's used in a way that TypeScript cannot detect? But note: noUnusedLocals and noUnusedParameters are about variables that are never read. So if we have a property that is only accessed by string, TypeScript might think it's unused.
So we might have to suppress the error for that variable with a comment.
This is a trade-off.
We might decide to enable noUnusedLocals and noUnusedParameters and then for each false positive, we add a comment.
But then we are adding a lot of comments. Alternatively, we can disable the checks for the entire file? Not ideal.
So maybe we do:
- Enable `noUnusedLocals` and `noUnusedParameters` and fix what we can.
- For the ones that are false positives (due to framework magic), we add `// @ts-expect-error` with a comment.
But note: // @ts-expect-error is for expected type errors, not for unused variables. Actually, it works for any error.
However, there is a specific rule for unused variables? We can use:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
if we are using ESLint? But we are talking about TypeScript's own checks.
TypeScript's noUnusedLocals and noUnusedParameters are compiler options, and we can suppress them with:
// @ts-ignore
but that suppresses all errors on the next line.
Alternatively, we can use:
// @ts-expect-error
and then the error that is expected must match the one we get? Actually, `@ts-expect-error` will suppress the next line's error only if the error message matches the one that appears? Not exactly: it suppresses any error on the next line, but if there is no error, it will cause an error itself.
So we can use:
// @ts-expect-error: property is used in template
and then the variable that is unused.
But note: noUnusedLocals and noUnusedParameters are reported on the line of the variable/parameter declaration.
So we can put the comment above the declaration.
However, this might be too many comments.
Another idea: we can disable these two checks and rely on ESLint's @typescript-eslint/no-unused-vars which might be more configurable? But then we are not using TypeScript's built-in.
Since we are focusing on TypeScript's strictness, we might want to enable them and deal with the false positives.
But note: the strict flag does not include these two, so we are going beyond strict.
We might decide to stop at the strict set and then later, if we want, we can enable these two.
So let's stick to the strict flags first (the ones that are part of strict).
The strict flag in TypeScript 4.0+ includes:
"strict": true,
which sets:
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitAny": true,
"noImplicitThis": true,
"alwaysStrict": true
And also:
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
But note: noImplicitReturns and noFallthroughCasesInSwitch are not part of the strict flag? Actually, they are separate.
According to the TypeScript docs (as of 4.9):
The `strict` flag enables:
--alwaysStrict
--noImplicitAny
--noImplicitThis
--strictBindCallApply
--strictFunctionTypes
--strictNullChecks
--strictPropertyInitialization
--noImplicitReturns
--noFallthroughCasesInSwitch
So actually, noImplicitReturns and noFallthroughCasesInSwitch are included in strict.
But wait, I just checked the TypeScript 5.0 docs:
The `strict` flag enables:
--alwaysStrict
--noImplicitAny
--noImplicitThis
--strictBindCallApply
--strictFunctionTypes
--strictNullChecks
--strictPropertyInitialization
--noImplicitReturns
--noFallthroughCasesInSwitch
So yes, they are included.
But note: noUnusedLocals and noUnusedParameters are not included.
So our plan:
Step 1: Enable the flags that are part of `strict` but not currently enabled, one by one (or we can enable `strict: true` and then fix? But we want to do it gradually).
Since `strict` is a meta-flag that sets multiple, we can either:
Option A: Disable `strict` and enable each flag individually in the order we want.
Option B: Keep `strict` off and enable the flags one by one (without using the `strict` flag).
I think Option B is better for gradual.
But note: if we have `strict: true` in `tsconfig.json`, then all the strict flags are on. So we must set `"strict": false` and then set each flag to true one by one.
However, if we are starting from a non-strict codebase, we might not have `strict` set at all, so we can just set each flag.
But if we have `strict: true` already, then we are already at the end? Not necessarily, because we might have `noUnusedLocals` and `noUnusedParameters` off.
So let's assume we are starting from a non-strict codebase.
Steps:
1. In `tsconfig.json`, set `"strict": false` (if it was true) and then set each of the strict flags to true one by one.
2. We'll follow the order above, but note that some flags might be already enabled by `strict`? We are turning off `strict` so we have to set each one.
Alternatively, we can leave `strict` on and then enable the additional flags? But then we are not doing gradual for the strict flags.
So we want to do:
- Turn off `strict` (if on) and then enable the individual flags in the order we choose.
But then we are not using the `strict` flag at all? We are setting the same flags but individually.
That's fine.
However, if we are starting from a codebase that has some of these flags already enabled, we can skip those.
So:
Let desiredFlags = [ 'noImplicitAny', 'strictNullChecks', ... ] in the order we want.
For each flag in desiredFlags:
if the flag is not already enabled (in tsconfig.json), then enable it and fix.
We can do this manually or with a script.
Since we are human, we can do:
Step 1: Check current `tsconfig.json` and note which strict flags are already on.
Step 2: For the ones that are off, enable them in the desired order (maybe the order above) and fix.
But note: the order might matter because enabling `strictNullChecks` before `noImplicitAny` might cause different errors? Actually, we want `noImplicitAny` first so that we don't have implicit `any` when we start dealing with `null` and `undefined`.
So let's stick to the order:
noImplicitAny -> strictNullChecks -> ...
But if `strictNullChecks` is already on and `noImplicitAny` is off, then we enable `noImplicitAny` first? That might cause a lot of errors because now we are going to catch implicit `any` that we didn't catch before.
So we should enable `noImplicitAny` first even if `strictNullChecks` is already on? Actually, if `strictNullChecks` is on, then we might have already fixed some `null` and `undefined` issues, but we might still have implicit `any` in other places.
So I think we should enable the flags in the order we listed, regardless of the current state, and fix the errors that appear.
But note: if we enable `noImplicitAny` and there are errors, we fix them. Then when we enable `strictNullChecks`, we might get new errors because now `null` and `undefined` are not assignable to every type.
So it's a two-step process for each flag.
But if we have both already enabled, then we are done for these two.
So the plan:
We have a list of flags in the order we want to enable (if not already enabled).
We go through the list:
For flag in flags:
if flag is not enabled:
enable flag
run tsc and fix errors
run tests
commit
Then move to next.
But what if we enable a flag and it causes errors that are related to a flag that we haven't enabled yet? For example, enabling `strictFunctionTypes` might cause errors that would have been caught by `noImplicitAny`? Actually, `noImplicitAny` is about implicit `any` in variable declarations and function parameters. `strictFunctionTypes` is about function type bivariance. They are orthogonal.
So I think the order we have is safe.
Let's list the flags again in our desired order (and note which are part of `strict`):
Part of `strict`:
noImplicitAny
strictNullChecks
strictFunctionTypes
strictBindCallApply
strictPropertyInitialization
noImplicitThis
alwaysStrict
noImplicitReturns
noFallthroughCasesInSwitch
Not part of `strict`:
noUnusedLocals
noUnusedParameters
exactOptionalPropertyTypes (TypeScript 4.4+)
useUnknownInCatchVariables (TypeScript 4.0+)
noImplicitOverride (TypeScript 4.3+)
We'll do the `strict` ones first in the order above, then the non-strict ones (if desired).
But note: `alwaysStrict` might be redundant if we are targeting ES6 or above? Because ES6 modules are strict by default. But if we are targeting ES5, then `alwaysStrict` will add `"use strict"` to every file.
So we might want to enable it for consistency.
Now, the non-strict ones:
`noUnusedLocals` and `noUnusedParameters` can be enabled at any time, but they might be noisy. We do them last.
`exactOptionalPropertyTypes` (TypeScript 4.4+): This changes the behavior of optional properties in object types. It's a good one to enable if we are using TypeScript 4.4+.
`useUnknownInCatchVariables` (TypeScript 4.0+): It changes the type of catch clause variables from `any` to `unknown`. This is a good safety feature.
`noImplicitOverride` (TypeScript 4.3+): It requires that overriding methods in a derived class use the `override` keyword. This is good for safety.
We can enable these after the strict set, but note that `noImplicitOverride` might require a lot of changes if we have a lot of inheritance.
So we might want to do:
After the strict set (which includes `noImplicitAny`, etc.):
Enable `useUnknownInCatchVariables` (if using TS4.0+)
Enable `exactOptionalPropertyTypes` (if using TS4.4+)
Enable `noImplicitOverride` (if using TS4.3+)
Then enable `noUnusedLocals` and `noUnusedParameters`.
But note: `noUnusedLocals` and `noUnusedParameters` might be affected by the above? Not really.
So let's finalize the order:
Strict flags (in the order we think is safe):
1. noImplicitAny
2. strictNullChecks
3. strictFunctionTypes
4. strictBindCallApply
5. strictPropertyInitialization
6. noImplicitThis
7. alwaysStrict
8. noImplicitReturns
9. noFallthroughCasesInSwitch
Then, if we are on a recent TypeScript:
10. useUnknownInCatchVariables (if TS >= 4.0)
11. exactOptionalPropertyTypes (if TS >= 4.4)
12. noImplicitOverride (if TS >= 4.3)
Then:
13. noUnusedLocals
14. noUnusedParameters
But note: `noImplicitOverride` might cause errors that require adding `override` keyword. This is straightforward.
However, if we have a base class that is from a third-party library and we override without `override`, we get an error. But we can add `override` keyword and it's safe.
So we can do it.
But note: if we have a method that overrides but we didn't intend to? Then `noImplicitOverride` will catch that. So it's a good check.
Now, we have to consider the TypeScript version. We might not have all these flags.
So we should check the TypeScript version and only enable the flags that are available.
We can do:
- Check the TypeScript version in the project (from `package.json` or `tsc --version`).
- Then, for each flag, check if the current TypeScript version supports it.
Alternatively, we can just try to set the flag and if `tsc` complains about an unknown flag, we skip it.
But we don't want to break the build. So we can:
- Run `tsc` with the flag and if it fails with an unknown flag error, we skip that flag.
However, we are editing `tsconfig.json` and then running `tsc`. If the flag is unknown, `tsc` will error and we will see it.
So we can:
For each flag in the list:
If the flag is not enabled in `tsconfig.json`:
Set it to true in `tsconfig.json`.
Run `tsc --noEmit` and check:
If we get an error that the flag is unknown, then remove the flag and skip.
Else, fix the errors and continue.
But note: if we are using an older TypeScript, we might not have the flag, so we skip.
However, we might want to upgrade TypeScript to get the latest flags? That's a separate decision.
We assume we are using a recent TypeScript.
Let's assume we are using TypeScript 5.0 or above.
Now, we write the steps in a markdown file or a script.
Since we are in a text-based response, I'll write the steps as a plan.
Practical steps:
Step 0: Make sure we have a branch for this work and that we run tests frequently.
Step 1: Check current `tsconfig.json` and note the current compiler options.
Step 2: For each flag in the list above:
a. If the flag is already set to true in `tsconfig.json`, skip.
b. Else, set the flag to true in `tsconfig.json`.
c. Run `npx tsc --noEmit` (or the project's build command that runs tsc) and note the errors.
d. Fix the errors. This might involve:
- Adding type annotations.
- Adjusting code to handle `null` and `undefined` (for `strictNullChecks`).
- Adding `override` keyword (for `noImplicitOverride`).
- Removing unused variables/parameters (for `noUnusedLocals` and `noUnusedParameters`).
- Adding `// @ts-expect-error` for false positives (with a comment explaining why).
e. Run the test suite.
f. If tests pass, commit the changes (both `tsconfig.json` and the fixed code).
g. If tests fail, debug and fix the broken tests (which might be due to the type changes?).
Step 3: After all flags, consider setting `"strict": true`? Actually, we have set all the flags that `strict` would set, so we can set `"strict": true` and remove the individual flags? But then we are back to one flag. We can do that at the end to simplify.
However, note: `strict` does not include `noUnusedLocals` and `noUnusedParameters`. So if we set `strict: true`, we would have to set `noUnusedLocals` and `noUnusedParameters` separately again.
But we already set them individually? We can do:
After setting all the flags (including `noUnusedLocals` and `noUnusedParameters`), we can set `"strict": true` and then remove the individual flags that are part of `strict`? But then we are removing the individual flags and relying on `strict`.
However, if we set `strict: true`, it will set all the strict flags (including `noImplicitReturns` and `noFallthroughCasesInSwitch` which we already set). So we can remove the duplicates.
But note: if we set `strict: true` and then set `noUnusedLocals: true` and `noUnusedParameters: true`, that's fine.
Alternatively, we can leave the individual flags and not set `strict`. It's the same.
I think we can leave the individual flags and not set `strict` because we want to be explicit about which flags are on.
But if we want to use the `strict` flag for simplicity, we can set `strict: true` and then set the non-strict ones (`noUnusedLocals`, `noUnusedParameters`) separately.
Let's decide:
We have set:
noImplicitAny: true
strictNullChecks: true
... (all the strict ones)
Then we can set:
"strict": true,
and then remove all the individual strict flags? But then we are relying on `strict` to set them. And then we add:
"noUnusedLocals": true,
"noUnusedParameters": true,
But note: `strict` also sets `noImplicitReturns` and `noFallthroughCasesInSwitch`, which we already set.
So if we set `strict: true` and then set `noUnusedLocals` and `noUnusedParameters` to true, we are done.
But we might have set other non-strict flags (like `useUnknownInCatchVariables`). We can set them too.
So the final `tsconfig.json` might look like:
{
"compilerOptions": {
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"useUnknownInCatchVariables": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true
}
}
But note: `useUnknownInCatchVariables` and `exactOptionalPropertyTypes` and `noImplicitOverride` are not part of `strict`, so we set them separately.
However, if we are on an older TypeScript that doesn't support these, we don't set them.
So we can do:
After enabling all the flags individually (including the non-strict ones), we can set `"strict": true` and remove the individual strict flags? But then we are removing the explicit setting of each strict flag.
I think it's cleaner to set `strict: true` and then set the additional flags.
But we did the work by enabling each strict flag individually. So at the end, we can:
- Remove all the individual strict flags (the ones that are part of `strict`).
- Set `"strict": true`.
Then we have the same effect and a simpler config.
However, note that `strict` does not include `noUnusedLocals` and `noUnusedParameters`, so we leave those.
But wait: what about the non-strict flags we enabled (like `useUnknownInCatchVariables`)? We leave them.
So the final step:
After we have enabled all the flags (both strict and non-strict) individually and fixed, we can:
- Remove all the individual flags that are part of `strict` (i.e., the 9 flags listed above).
- Set `"strict": true`.
Then we have:
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"useUnknownInCatchVariables": true,
... etc.
This is cleaner.
But note: if we remove the individual flags and set `strict: true`, we are not changing the behavior (assuming we had all the strict flags set individually). So it's safe.
So we can do:
Step N: After all the flags (including the non-strict ones) are set and working, we can set `"strict": true` and remove the individual strict flags.
However, we must be cautious: if we missed a strict flag, then setting `strict: true` will turn it on and we might have errors. But we should have fixed all errors when we enabled each flag, so it should be safe.
But what if we skipped a flag because it was already on? Then we didn't fix for that flag? Actually, we fixed for each flag when we enabled it. So if a flag was already on, we didn't fix for it because we assumed it was already fixed? But maybe it was on and there were errors? Then we would have existing errors.
So we must make sure that for every flag that is on (whether we enabled it in this process or it was already on) we have fixed the errors.
So before setting `strict: true`, we should run `tsc` with all the current flags and ensure no errors.
Then, when we set `strict: true` and remove the individual flags, we are just replacing the same set of flags with `strict: true`.
So it's safe.
But note: if we have a flag that is not part of `strict` but we set it, and then we set `strict: true`, we are not removing that flag. So we are just replacing the strict flags with `strict: true`.
So the plan:
Phase 1: For each flag in the list (both strict and non-strict) that is not already enabled, enable it and fix.
Phase 2: After all flags are enabled and fixed, set `"strict": true` and remove the individual strict flags (the 9 flags).
But wait: what if we have `strict: true` already and then we enable individual flags? Then we are turning off `strict` and setting individual flags? That might be confusing.
So let's assume we start with `strict: false` (or no `strict` at all) and we set each flag individually.
Then at the end, we set `strict: true` and remove the individual strict flags.
But if we started with `strict: true`, then we are already done for the strict flags? Not exactly, because we might have not fixed all errors for each flag? Actually, if `strict` was on, then all the strict flags are on, but we might have errors.
So we should:
If we start with `strict: true`, then we already have all the strict flags on, but we might have errors. So we should fix the errors for the strict flags first (by running `tsc` and fixing). Then we can set `strict: true` (it's already true) and then enable the non-strict flags.
But we want to do it gradually? If `strict` was already on, then we are not doing gradual for the strict flags. We are just fixing the existing errors.
So we can:
Step 1: If `strict` is true, then we have all the strict flags on. We run `tsc` and fix all the errors (for the strict flags). Then we move to non-strict flags.
Step 2: If `strict` is false, then we enable each strict flag one by one (as above) and fix.
Then at the end, we set `strict: true` (if we started with `strict: false`) and remove the individual strict flags.
But if we started with `strict: true`, we leave it as is.
So the process is:
Let currentStrict = tsconfig.compilerOptions.strict (if set, otherwise false)
If currentStrict is true:
Then we have all strict flags on? Actually, `strict` sets them, but we can override individual flags? If we set `strict: true` and then set `noImplicitAny: false`, then `noImplicitAny` will be off? Actually, `strict` sets the defaults, but if we set an individual flag after `strict`, it will override.
So we should check each strict flag individually to see if they are on.
But for simplicity, if `strict` is true, we assume all strict flags are on? Not necessarily, because we might have overridden.
So better to check each flag individually.
We'll do:
For each flag in the strict flags list:
if the flag is not set to true in tsconfig (and not set by `strict`? But if `strict` is true, then the flag is true by default, unless overridden).
Actually, the way TypeScript works: if `strict` is true, then all the strict flags are true by default, but if we set an individual flag to false, it will be false.
So we have to check the effective value.
We can run `tsc --showConfig` to see the effective config? Or we can parse the tsconfig and apply the defaults?
This is getting complex.
Alternatively, we don't care about the current state of `strict`. We just want to set each flag to true individually and fix. Then at the end, we set `strict: true` and remove the individual strict flags.
So:
Step 1: Set `"strict": false` in `tsconfig.json` (if it was true) to avoid having `strict` override our individual flags? Actually, if we set `strict: false` and then set individual flags, we are in control.
Step 2: Then for each flag in the list (strict and non-strict) that we want, set it to true and fix.
Step 3: After all are fixed, set `"strict": true` and remove the individual strict flags.
But note: if we set `strict: false` and then set all the strict flags individually, then setting `strict: true` at the end will set them again? Actually, if we have set the individual flags to true, then setting `strict: true` will set them again to true (they are already true). So it's harmless.
And then we remove the individual strict flags, so we are left with:
"strict": true,
... (non-strict flags)
This is clean.
So:
Phase 1: Turn off `strict` (if on) by setting `"strict": false` in `tsconfig.json`.
Phase 2: Enable each flag (both strict and non-strict) in the desired order and fix.
Phase 3: Set `"strict": true` and remove the individual strict flags (the 9 flags) from `tsconfig.json`.
But wait: what if we are on an older TypeScript that doesn't have some of the strict flags? Then we cannot set them. So we skip.
And then at the end, when we set `strict: true`, it will set only the flags that are available? Actually, `strict` is a meta-flag that sets the flags that are available in that version.
So if we are on an older TypeScript, `strict` might not set the new flags.
But we are setting the flags individually only if they are available? We can check the TypeScript version.
Alternatively, we can try to set the flag and if it fails, skip.
Since we are doing this manually, we can check the TypeScript version and the available flags.
Let's assume we are on a recent TypeScript (>=5.0).
So the plan:
1. In `tsconfig.json`, set `"strict": false` (if it was true) and then for each flag in the list (both strict and non-strict) that we want to enable:
a. Add the flag with value `true` (if not already present).
b. Run `tsc --noEmit` and fix errors.
c. Run tests.
d. Commit.
2. After all flags are enabled and fixed, change `tsconfig.json` to:
- Remove all the individual strict flags (the 9 flags).
- Set `"strict": true`.
3. Run `tsc --noEmit` and tests again to ensure nothing broke.
But note: if we remove the individual strict flags and set `strict: true`, we are relying on `strict` to set them. But what if we are on an older TypeScript and `strict` doesn't set a flag that we had set individually? Then we would lose that flag.
So we must be sure that the TypeScript version we are using supports all the strict flags we want.
We can check the TypeScript version and the list of flags that `strict` sets in that version.
Alternatively, we can leave the individual strict flags and not set `strict` at all? Then we are being explicit.
I think being explicit is better because we know exactly which flags are on.
So we can skip step 3 (setting `strict: true` and removing individual flags) and just leave the individual flags.
But then we have a long list of flags.
It's a trade-off.
Given that we are doing this for safety, I think being explicit is better. So we leave the individual flags.
Then the final `tsconfig.json` will have:
{
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true,
...,
"noUnusedLocals": true,
"noUnusedParameters": true,
"useUnknownInCatchVariables": true,
...
}
}
And we don't set `strict`.
But note: if we upgrade TypeScript in the future, we might have to add new flags? We can then add them individually.
So let's not set `strict` and keep the individual flags.
Then the plan is:
Step 0: Ensure `tsconfig.json` has no `strict` flag (or set `strict: false`).
Step 1: For each flag in the list (in order) that is not already enabled, enable it and fix.
We are done.
But note: the list includes both strict and non-strict flags. We are enabling them all.
However, we might not want to enable `noUnusedLocals` and `noUnusedParameters` if they cause too many false positives? Then we skip them.
So the list is:
Strict flags (9):
noImplicitAny
strictNullChecks
strictFunctionTypes
strictBindCallApply
strictPropertyInitialization
noImplicitThis
alwaysStrict
noImplicitReturns
noFallthroughCasesInSwitch
Non-strict flags (optional, but recommended if supported):
useUnknownInCatchVariables (TS>=4.0)
exactOptionalPropertyTypes (TS>=4.4)
noImplicitOverride (TS>=4.3)
Then:
noUnusedLocals
noUnusedParameters
We can decide to skip `noUnusedLocals` and `noUnusedParameters` if they are too noisy.
So we can have two phases:
Phase 1: Strict flags (9)
Phase 2: Non-strict flags (the three above)
Phase 3: noUnusedLocals and noUnusedParameters (if desired)
And we do each phase in the order above.
Now, let's write the steps as a script-like plan.
Since we are in a text, I'll write a markdown checklist.
But note: we might have to do this over multiple days/weeks.
We can create a GitHub project or a ticket for each flag.
Alternatively, we can do it in one PR per flag? That might be too many PRs.
We can do:
One PR per phase? Or one PR for all?
Since we are fixing errors, we might want to do one PR per flag to keep the changes small and reviewable.
But if we have a lot of errors, one PR might be huge.
So we can do:
For each flag:
- Create a branch.
- Enable the flag.
- Fix the errors (might be many files).
- Run tests.
- Create a PR.
Then merge each PR one by one.
This way, we can review each set of changes.
But if we have many flags, we have many PRs.
Alternatively, we can do one PR that enables all flags and fixes all errors? That would be a huge PR.
So I think one PR per flag is better for review, but might be heavy on the CI and branch management.
We can also do:
One PR for the strict flags (9) and then one PR for the non-strict flags (3) and then one PR for the unused flags (2). That's 3 PRs.
But within each PR, we are enabling one flag at a time? Actually, we can enable all the flags in that phase in one go and fix all the errors? That might be too many errors at once.
So we go back to one flag at a time.
Given the complexity, we might do:
Phase 1: Enable all strict flags at once and fix? But then we have 9 flags at once and a lot of errors.
I think we should do one flag at a time.
So:
We'll have 9 PRs for the strict flags, then 3 for the non-strict, then 2 for the unused.
That's 14 PRs. That's a lot.
Alternatively, we can group the strict flags that are closely related:
Group 1: noImplicitAny and strictNullChecks (because they are the big ones)
Group 2: strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis (these are about functions and classes)
Group 3: alwaysStrict, noImplicitReturns, noFallthroughCasesInSwitch (these are about code style)
Then 3 PRs for strict, then 3 for non-strict, then 2 for unused -> 8 PRs.
But still a lot.
Another idea: we can enable all the strict flags in one PR and then fix the errors in that PR. Then we do the non-strict in another PR, then the unused in another.
That's 3 PRs.
But the first PR might be huge.
We have to balance between the size of the PR and the number of PRs.
Since we are a team, we can do:
PR 1: Enable all strict flags and fix errors. (This might be huge, but we can break the fix into multiple commits in the PR.)
Then PR 2: Enable the non-strict flags and fix.
Then PR 3: Enable the unused flags and fix.
Then we are done.
But note: the non-strict flags might depend on the strict flags? Not really.
So we can do:
PR 1: Enable all strict flags (the 9) and fix all errors.
PR 2: Enable useUnknownInCatchVariables, exactOptionalPropertyTypes, noImplicitOverride (if supported) and fix.
PR 3: Enable noUnusedLocals and noUnusedParameters and fix.
That's 3 PRs.
But what if we don't want to enable the non-strict flags? Then we do 2 PRs.
I think 3 PRs is manageable.
However, if we are starting from a codebase that already has some of these flags on, we can adjust.
Let's assume we start with no strict flags and no non-strict flags.
Steps for PR1:
- Set `"strict": false` (if not already) and then set each of the 9 strict flags to true.
- Fix all errors.
- Run tests.
- Commit.
Then PR2: set the non-strict flags (the three) and fix.
Then PR3: set the unused flags and fix.
But note: the non-strict flags might be independent, so we can enable them in any order? We can enable all three at once and fix.
And the unused flags: we can enable both at once and fix.
So:
PR1: 9 strict flags.
PR2: 3 non-strict flags.
PR3: 2 unused flags.
That's 3 PRs.
But what if we are on an older TypeScript that doesn't have some of the non-strict flags? Then we skip them in PR2.
And for the unused flags, we might not want to enable them? Then skip PR3.
So we can have:
PR1: always (the 9 strict flags)
PR2: if we want the non-strict flags and they are supported.
PR3: if we want the unused flags and we are ready to deal with the noise.
Now, we have to consider that enabling all 9 strict flags at once might produce a lot of errors. But we are going to fix them all in one PR.
This might be a huge PR. But we can break the fixing into multiple commits within the PR.
Alternatively, we can do:
In PR1, we enable the 9 flags and then fix the errors in multiple commits:
Commit 1: fix noImplicitAny errors.
Commit 2: fix strictNullChecks errors.
... etc.
But then we are enabling all flags at once, so the errors are intermingled. We might fix an error that is due to `strictNullChecks` in the same file that also has `noImplicitAny` errors.
So it's better to fix by error type? Or by file?
Actually, we are going to fix all errors anyway. So we can fix by file or by module.
But the point of the gradual ratchet is to enable one flag at a time. So if we enable all 9 at once, we lose the gradual aspect.
So maybe we should do 9 PRs? But that's a lot.
Compromise:
We can enable the 9 flags in two groups:
Group A: noImplicitAny, strictNullChecks
Group B: the rest (7 flags)
Then PR1: Group A.
PR2: Group B.
Then PR3: non-strict.
PR4: unused.
That's 4 PRs.
But Group A (noImplicitAny and strictNullChecks) are the most invasive. So we do them separately? Actually, we can do them together because they are orthogonal? Not entirely: `strictNullChecks` will cause errors that might be due to missing `any`? But we are already fixing `noImplicitAny` so we will have types.
I think we can do:
PR1: noImplicitAny and strictNullChecks (the two biggest) and fix.
PR2: the remaining 7 strict flags and fix.
PR3: non-strict.
PR4: unused.
That's 4 PRs.
But note: `noImplicitAny` and `strictNullChecks` are the most common source of errors, so we might want to do them separately? Actually, doing them together might be better because when we fix `noImplicitAny`, we add types, and then `strictNullChecks` might require adjusting those types for `null` and `undefined`.
So we can do them together.
Let's do:
PR1: Enable noImplicitAny and strictNullChecks. Fix all errors.
PR2: Enable the other 7 strict flags. Fix.
PR3: Enable non-strict flags (if any). Fix.
PR4: Enable unused flags. Fix.
That seems manageable.
But what if we have a lot of errors in PR1? Then PR1 is huge.
We can break PR1 into multiple commits by file or by module.
But the PR will still be large.
Alternatively, we can do:
PR1: noImplicitAny only.
PR2: strictNullChecks only.
Then PR3: the rest.
That's 3 PRs for strict.
Then PR4: non-strict.
PR5: unused.
That's 5 PRs.
I think we should do one flag at a time for the big two, and then group the rest.
So:
PR1: noImplicitAny
PR2: strictNullChecks
PR3: the other 7 strict flags
PR4: non-strict
PR5: unused
That's 5 PRs.
But note: the other 7 strict flags might not cause as many errors? We can group them.
Let's do:
PR1: noImplicitAny
PR2: strictNullChecks
PR3: strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, alwaysStrict, noImplicitReturns, noFallthroughCasesInSwitch (7 flags)
PR4: useUnknownInCatchVariables, exactOptionalPropertyTypes, noImplicitOverride (if supported)
PR5: noUnusedLocals, noUnusedParameters
That's 5 PRs.
Now, we have to consider that enabling multiple flags in PR3 might cause errors that are related? But we fix them all.
This seems reasonable.
So the plan:
Phase 1: PR1 - Enable `noImplicitAny` and fix.
Phase 2: PR2 - Enable `strictNullChecks` and fix.
Phase 3: PR3 - Enable the remaining 7 strict flags and fix.
Phase 4: PR4 - Enable non-strict flags (if supported) and fix.
Phase 5: PR5 - Enable unused flags and fix.
But note: after PR2, we have `noImplicitAny` and `strictNullChecks` on. Then in PR3, we enable the other 7. We might get new errors that are due to the combination? But we fix them.
Now, we have to write the steps for each PR.
For each PR:
Step 1: Update `tsconfig.json` to set the flags for that PR to true (and make sure `strict` is false).
Step 2: Run `tsc --noEmit` and collect the errors.
Step 3: Fix the errors. We might need to:
- Add type annotations.
- Handle `null` and `undefined` (for `strictNullChecks`).
- Add `override` keyword (for `noImplicitOverride`).
- Remove unused variables/parameters (for `noUnusedLocals` and `noUnusedParameters`).
- For `noFallthroughCasesInSwitch`, add `break` or `return` or comment `// falls through`? Actually, `noFallthroughCasesInSwitch` requires that every case must end with `break`, `return`, `throw` or a comment `// falls through`? Actually, the flag requires that there is no fallthrough case. So if we have:
switch (x) {
case 1:
doA();
case 2:
doB();
}
This is an error because case 1 falls through. We must break or comment.
We can add `break;` or `return;` or `throw;` or a comment `// falls through`? Actually, the comment must be `// falls through`? The TypeScript docs say: "You can add a `// falls through` comment to suppress the error for a specific case."
So we can do:
case 1:
doA();
// falls through
But note: the error is on the line of the next case? Actually, the error is on the line of the case that falls through? Let me check.
Actually, the error is on the first case that falls through? Or on the second case?
Example:
switch (x) {
case 1:
console.log(1);
case 2: // Error: Fallthrough case in switch.
console.log(2);
}
The error is on the second case? Or the first?
In my experience, the error is on the line of the second case (the one that is fallen into). But the fix is to mark the first case as intentional fallthrough.
So we can add a comment `/* falls through */` at the end of the first case.
But the error message says: "Fallthrough case in switch." and points to the second case.
So we fix by adding a comment in the first case.
But note: the rule is that every case must end with `break`, `return`, `throw`, or a comment that says `/* falls through */` or `// falls through`.
So we can fix by:
case 1:
doA();
// falls through
Then the error goes away.
So for each fallthrough, we add the comment.
- For `alwaysStrict`, we might need to remove `"use strict"` from files? Actually, `alwaysStrict` will emit `"use strict"` in every file, and also parse in strict mode. If we already have `"use strict"` in some files, that's okay. But we might have to adjust code that is not strict mode compatible? Actually, `alwaysStrict` doesn't change the runtime behavior if we already have `"use strict"`? It might duplicate? TypeScript will not duplicate if we have `"use strict"` already? I think it will emit `"use strict"` only if we don't have it? Actually, TypeScript doesn't add `"use strict"` if we are targeting ES6 modules because they are strict by default. But if we are targeting ES5, then `alwaysStrict` will add `"use strict"` to every file.
So we might have to adjust code that is not strict mode compatible? But we are already in strict mode? Not necessarily.
This might require changes if we have code that relies on non-strict behavior (like with `eval` or `arguments` or duplicate parameter names). But we are using TypeScript, so we might not have those.
So we might get errors from `alwaysStrict`? Actually, `alwaysStrict` is a parser flag and an emit flag. It will cause the parser to parse in strict mode, which might disallow some syntax. But we are using TypeScript, so we are already using valid JavaScript/TypeScript.
I think `alwaysStrict` is safe.
- For `noImplicitReturns`, we have to make sure every code path in a function returns a value.
- For `noFallthroughCasesInSwitch`, we have to handle every case.
Step 4: Run tests.
Step 5: Commit.
Then move to next PR.
But note: we are enabling multiple flags in PR3 (7 flags). We might get errors that are due to one flag or multiple. We fix them all.
This is acceptable.
Now, we have to consider that some errors might be in third-party code? We are not fixing third-party code. We are only fixing our code.
And if we are using `skipLibCheck` (which is common), then we don't check third-party declaration files.
So we are safe.
Now, let's write the steps for each PR.
However, we might have to adjust the order if we find that enabling a flag causes errors that are easier to fix after another flag? But we are doing the big ones first.
I think this order is fine.
Let's write a table of the flags and what they do, and then the steps for each PR.
But the question asks for a ratchet, so we are enabling one by one.
Given the complexity, I think we should do:
PR1: noImplicitAny
PR2: strictNullChecks
PR3: strictFunctionTypes
PR4: strictBindCallApply
PR5: strictPropertyInitialization
PR6: noImplicitThis
PR7: alwaysStrict
PR8: noImplicitReturns
PR9: noFallthroughCasesInSwitch
PR10: useUnknownInCatchVariables (if supported)
PR11: exactOptionalPropertyTypes (if supported)
PR12: noImplicitOverride (if supported)
PR13: noUnusedLocals
PR14: noUnusedParameters
That's 14 PRs. That's a lot, but each PR might be small? Not necessarily.
Alternatively, we can group the less invasive ones:
Group 1: noImplicitAny
Group 2: strictNullChecks
Group 3: strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis (these are about function and class types)
Group 4: alwaysStrict, noImplicitReturns, noFallthroughCasesInSwitch (these are about code structure)
Group 5: non-strict (3)
Group 6: unused (2)
That's 6 PRs.
I think 6 PRs is acceptable.
But note: the errors in Group 3 might be similar? They are all about function and class types.
So we can do:
PR1: noImplicitAny
PR2: strictNullChecks
PR3: Group3 (4 flags)
PR4: Group4 (3 flags)
PR5: Group5 (3 flags)
PR6: Group6 (2 flags)
That's 6 PRs.
Now, we have to make sure that when we enable Group3 (4 flags), we don't get errors that are due to `noImplicitAny` or `strictNullChecks`? But we already fixed those in PR1 and PR2.
So it should be okay.
Let's do that.
Steps for each PR:
PR1: noImplicitAny
- Set `"noImplicitAny": true` in `tsconfig.json`.
- Run `tsc --noEmit` and fix all errors (add type annotations).
- Run tests.
- Commit.
PR2: strictNullChecks
- Set `"strictNullChecks": true` in `tsconfig.json`.
- Run `tsc --noEmit` and fix all errors (handle `null` and `undefined`).
- Run tests.
- Commit.
PR3: Group3 (4 flags)
- Set `"strictFunctionTypes": true`, `"strictBindCallApply": true`, `"strictPropertyInitialization": true`, `"noImplicitThis": true`.
- Run `tsc --noEmit` and fix.
- Run tests.
- Commit.
PR4: Group4 (3 flags)
- Set `"alwaysStrict": true`, `"noImplicitReturns": true`, `"noFallthroughCasesInSwitch": true`.
- Run `tsc --noEmit` and fix.
- Run tests.
- Commit.
PR5: Group5 (non-strict, 3 flags, if supported)
- Set `"useUnknownInCatchVariables": true` (if TS>=4.0), `"exactOptionalPropertyTypes": true` (if TS>=4.4), `"noImplicitOverride": true` (if TS>=4.3).
- Run `tsc --noEmit` and fix.
- Run tests.
- Commit.
PR6: Group6 (unused, 2 flags)
- Set `"noUnusedLocals": true`, `"noUnusedParameters": true`.
- Run `tsc --noEmit` and fix.
- Run tests.
- Commit.
After PR6, we are done.
But note: we might want to set `"strict": true` at the end? We have set all the strict flags individually. We can leave them or set `strict: true` and remove the individual strict flags.
I think we leave them as is.
Now, we have to consider that some of these flags might not be available. We check the TypeScript version and only set the ones that are available.
We can do:
For each flag in the group, check if the current TypeScript version supports it.
How to check? We can run `tsc --version` and compare.
But we can also just set it and if `tsc` complains, we remove it and skip.
Since we are doing this manually, we can check the TypeScript version and the release notes.
Alternatively, we can have a script that:
- Reads the TypeScript version.
- For each flag, checks if the flag is supported (by trying to compile with that flag and see if it errors about unknown flag).
But we are doing it in PRs, so we can:
In each PR, we set the flags for that group.
Then we run `tsc --noEmit`. If we get an error about an unknown flag, we remove that flag and note that we are skipping it.
But then we might have to adjust the PR.
Better to check the TypeScript version and the supported flags before starting.
Let's assume we are on TypeScript 5.0. Then all flags are supported.
So we proceed.
Now, we have to write the steps for each group.
But note: the groups are arbitrary. We can do one flag at a time if we want.
Given the size of the codebase, we might need to adjust.
But this is a plan.
Let me write the steps in a more formal way.
We'll create a document that outlines:
- The current `tsconfig.json` (backup).
- The order of enabling flags.
- For each flag/group, the steps to follow.
But since we are in a text, I'll write a summary.
Summary:
1. Ensure you have a clean working tree and a branch for each PR.
2. For each group (as defined above):
a. Update `tsconfig.json` to set the flags in the group to `true` (and ensure `"strict": false` is set if not already).
b. Run `npx tsc --noEmit` and note the errors.
c. Fix the errors, which may involve:
- Adding type annotations (for `noImplicitAny`).
- Adjusting code to handle `null` and `undefined` (for `strictNullChecks`).
- Adding `override` keyword (for `noImplicitOverride`).
- Adding `break` or `return` or `throw` or `// falls through` for `noFallthroughCasesInSwitch`.
- Ensuring all code paths return a value (for `noImplicitReturns`).
- Removing unused variables/parameters (for `noUnusedLocals` and `noUnusedParameters`).
- For `useUnknownInCatchVariables`, change `catch (err: any)` to `catch (err: unknown)` and then adjust the catch block to handle `unknown`.
- For `exactOptionalPropertyTypes`, we might need to adjust interfaces with optional properties? This flag makes optional properties not assignable to `undefined`? Actually, it changes the type of optional properties to be `T | undefined`? Wait, the exact optional property types flag makes it so that an optional property `x?` is treated as `x: T | undefined`? Actually, the default behavior is that `x?` is `x: T | undefined`? No, the default is that `x?` is `x: T | undefined`? I'm confused.
Let me check:
interface Foo {
x?: string;
}
declare const foo: Foo;
foo.x = undefined; // is this allowed?
By default, it is allowed because `x?: string` is equivalent to `x: string | undefined`? Actually, no: `x?: string` means that the property `x` can be omitted, and if it exists, it must be a `string`. But we can set it to `undefined`? Actually, we can set it to `undefined` because `undefined` is assignable to `string`? No, `undefined` is not assignable to `string`. So by default, `x?: string` does not allow `undefined`?
Wait, I think I'm wrong.
Let me test:
interface Foo {
x?: string;
}
const foo: Foo = { x: undefined }; // error: Type 'undefined' is not assignable to type 'string'
So by default, `x?: string` does not allow `undefined`? Then what does it allow? It allows the property to be absent. But if the property is present, it must be a `string`.
Now, with `exactOptionalPropertyTypes`, it changes the behavior so that `x?: string` is equivalent to `x: string | undefined`? Actually, the flag is called "exact optional property types", and it makes optional properties of type `T` become `T | undefined`? I think it's the opposite: it makes them not accept `undefined`?
Let me read the TypeScript 4.4 release notes:
Under strict, optional properties and parameters with types that don't include undefined are now considered to be of type T | undefined when reading, but still disallowed when writing.
Actually, the release notes say:
In TypeScript 4.4, the --exactOptionalPropertyTypes flag changes the behavior of optional properties and parameters. When this flag is enabled, the type system treats optional properties as though they were declared with `T | undefined` in their type, rather than as `T`. This more closely matches the runtime behavior where an omitted property will have the value `undefined`.
So with `exactOptionalPropertyTypes`, `x?: string` becomes `x: string | undefined`? Actually, it means that when you read `x`, you get `string | undefined`. But when you write, you cannot write `undefined`? Wait, the release notes say:
For example, consider the following example:
interface Person {
name?: string;
}
declare const p: Person;
p.name; // string | undefined
p.name = 5; // error
With the new flag, the type of `p.name` becomes `string | undefined`, but assigning `undefined` is still an error because the property is optional, not because it accepts `undefined`.
Actually, the change is about reading: without the flag, `p.name` is `string` (because optional properties are considered to be present or not, but if present, they are `string`). With the flag, `p.name` is `string | undefined` because the property might be absent (which is `undefined`).
But writing: without the flag, you cannot write `undefined` to an optional property of type `string`? Actually, you can write `undefined`? Let me test:
interface Foo {
x?: string;
}
const foo: Foo = {};
foo.x = undefined; // is this allowed?
In TypeScript 4.3, this is allowed? Actually, I think it is allowed because `undefined` is assignable to `string`? No, `undefined` is not assignable to `string`.
But wait, `x?: string` means that the property `x` can be omitted, and if it is present, it must be a `string`. So writing `undefined` is not allowed because `undefined` is not a `string`.
So with or without the flag, writing `undefined` is an error.
The flag changes the reading: without the flag, `foo.x` is of type `string` (because if the property is present, it's `string`, and if absent, we are reading an absent property which is `undefined`? Actually, reading an absent property of an object that has an optional property of type `string` returns `undefined`, but TypeScript without the flag thinks it's `string`? That's unsafe.
So the flag makes the reading type `string | undefined` which is safe.
So we might have to adjust code that reads optional properties and assumes they are `string` when they could be `undefined`.
So we might need to add checks for `undefined`.
This could be a lot of work.
So we might want to skip `exactOptionalPropertyTypes` if we have a lot of optional properties.
But it's a safety improvement.
We'll include it in PR5 and fix the errors.
- For `noImplicitOverride`, we have to add `override` keyword to methods that override a base class method.
- For `useUnknownInCatchVariables`, we change `catch (err: any)` to `catch (err: unknown)` and then handle `unknown` (by checking the type or using `unknown`).
d. After fixing, run `npx tsc --noEmit` to ensure no errors.
e. Run tests.
f. Commit and create a PR.
3. After all groups, we have all the flags we want.
This is the plan.
But note: we might have to repeat for multiple branches if we are working on a team? We can do one branch for each PR.
Now, let's write the steps for each group in detail.
However, the question asks to "compose a TypeScript strictness ratchet gradually enabling flags, refactors, and safety metrics."
We have the flags and refactors. What about safety metrics?
We can also consider adding:
- Code coverage (using Istanbul/nyc) and enforce a minimum (e.g., 80%).
- Cyclomatic complexity (using ESLint or other tools) and enforce a maximum.
But these are not TypeScript compiler flags.
The question might be about TypeScript's strictness, but we can also include other safety metrics.
However, the main focus is on TypeScript's strict flags.
So we'll stick to TypeScript.
But we can mention that we can also set up ESLint with `@typescript-eslint` and enable rules that enforce safety, like:
- `@typescript-eslint/no-floating-promises`
- `@typescript-eslint/await-thenable`
- etc.
But that's beyond the scope.
So we focus on TypeScript.
Now, let's write the plan in a more structured way.
We'll write:
# TypeScript Strictness Ratchet Plan
## Prerequisites
- TypeScript version: [check and note]
- Test suite: [ensure we have tests]
- Current `tsconfig.json`: [backup]
## Step 0: Preparation
- Set `"strict": false` in `tsconfig.json` (if it was true).
- Ensure we are on a clean branch.
## Group 1: noImplicitAny
- Enable `"noImplicitAny": true`.
- Fix errors by adding type annotations.
- Run tests.
- Commit.
## Group 2: strictNullChecks
- Enable `"strictNullChecks": true`.
- Fix errors by handling `null` and `undefined` (using `?`, `!`, or explicit checks).
- Run tests.
- Commit.
## Group 3: strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis
- Enable the four flags.
- Fix errors (might involve adjusting function types, adding `this` types, initializing class properties, etc.)
- Run tests.
- Commit.
## Group 4: alwaysStrict, noImplicitReturns, noFallthroughCasesInSwitch
- Enable the three flags.
- Fix errors (add `// falls through` for switch, ensure all code paths return, and note that `alwaysStrict` might not cause errors but we check).
- Run tests.
- Commit.
## Group 5: non-strict flags (if supported)
- Check TypeScript version and enable:
- `useUnknownInCatchVariables` (TS>=4.0)
- `exactOptionalPropertyTypes` (TS>=4.4)
- `noImplicitOverride` (TS>=4.3)
- Fix errors (adjust catch variables, optional property reads, add `override` keyword).
- Run tests.
- Commit.
## Group 6: unused flags
- Enable `"noUnusedLocals": true` and `"noUnusedParameters": true`.
- Fix errors (remove unused code or use the variables/parameters, or add `// @ts-expect-error` for false positives).
- Run tests.
- Commit.
## Done
We can also add a step at the end to set `"strict": true` and remove the individual strict flags? But we already set them individually.
We leave as is.
Now, we have to consider that some errors might be in third-party code? We use `skipLibCheck` to avoid checking node_modules.
So we should have `"skipLibCheck": true` in `tsconfig.json` to avoid errors in third-party libraries.
We assume that is already set.
Also, we might have to adjust `tsconfig.json` for the project (like `target`, `module`, etc.) but that's separate.
Now, let's write the answer.
We'll write a detailed plan.
But note: the user might have a different order in mind. We can adjust.
Since the user asked for a "ratchet", we are enabling flags gradually.
We'll provide the plan as above.
Also, we can mention that for each group, we might want to run `tsc --noEmit` and then use an automated tool to fix some errors? For example, `ts-migrate` can fix some `noImplicitAny` errors? But we are already in TypeScript.
There is a tool called `tsc-fix`? Not sure.
We can do manual fixing.
Now, let's write the answer.</think>
I'll outline a comprehensive TypeScript strictness ratchet strategy that progressively enables compiler flags, performs targeted refactors, and tracks safety metrics. This approach minimizes disruption while incrementally improving type safety.
Phase 0: Baseline Analysis
# Generate baseline metrics
npx tsc --noEmit > baseline_errors.txt
npx eslint . --ext .ts,.tsx > baseline_eslint.txt
npx madge --image graph.svg src/
npx type-coverage --report --precision 100 src/
Phase 1: Preparation
// tsconfig.json
{
"compilerOptions": {
"skipLibCheck": true,
"noEmit": true,
// Start with minimal strictness
"strict": false,
// Individual flags disabled initially:
"noImplicitAny": false,
"strictNullChecks": false,
// ... other flags false
}
}
Phase 2: Incremental Flag Enablement (Ratchet Order)
Group A: Foundational (Low disruption, high value)
noImplicitAny → Fix implicit any with type annotations
strictNullChecks → Add null guards, optional chaining, non-null assertions
noImplicitThis → Add explicit this types
Group B: Function/Class Safety
strictFunctionTypes → Fix bivariant function parameters
strictBindCallApply → Validate bind/call/apply usage
strictPropertyInitialization → Add definite assignment assertions (!) or constructor initialization
Group C: Control Flow
noImplicitReturns → Ensure all code paths return values
noFallthroughCasesInSwitch → Add break/return or // falls through comments
alwaysStrict → Ensure strict mode parsing
Group D: Advanced (Last)
exactOptionalPropertyTypes (TS 4.4+) → Distinguish optional vs. undefined
noImplicitOverride (TS 4.3+) → Add override keyword
useUnknownInCatchVariables (TS 4.0+) → Change catch (e: any) to unknown
Group E: Unused Code Detection
noUnusedLocals → Remove/comments unused variables
noUnusedParameters → Remove unused parameters or prefix with _
Phase 3: Refactor Patterns
Common Refactors by Flag:
For strictNullChecks:
// Before
function getUser(id: string) { return db.find(id); }
// After (safe)
function getUser(id: string): User | null {
return db.find(id) ?? null;
}
// Usage
const user = getUser('123');
if (user) { /* safe */ } // or user?.name
For strictFunctionTypes:
// Before (bivariant)
type Handler = (event: Event) => void;
const handlers: Handler[] = [];
handlers.push((e) => console.log(e)); // Unsafe, allowed
// After (contravariant)
type Handler = (event: Event) => void;
function addHandler(handler: (arg: Event) => void) { /* ... */ }
For exactOptionalPropertyTypes:
// Before
interface Config {
timeout?: number; // Could be undefined or missing
}
const c: Config = { timeout: undefined }; // Allowed but confusing
// After (needs explicit undefined)
interface Config {
timeout?: number | undefined;
}
// Or better:
interface Config {
timeout: number | undefined; // Explicit
}
Phase 4: Safety Metrics Dashboard
Create a ts-strictness-tracker.ts script:
interface StrictnessMetrics {
timestamp: string;
flagsEnabled: string[];
errorCount: number;
typeCoverage: number;
complexity: {
avgCyclomatic: number;
maxCyclomatic: number;
};
anyUsage: number;
nullishCoalescing: number;
optionalChaining: number;
}
// Run after each phase
const metrics: StrictnessMetrics = {
timestamp: new Date().toISOString(),
flagsEnabled: getEnabledFlags(),
errorCount: countTscErrors(),
typeCoverage: getTypeCoverage(),
// ... calculate complexity
};
// Store in metrics.jsonl for trend analysis
Phase 5: Implementation Workflow
For Each Flag Group:
- Enable flags in
tsconfig.json
- Run compiler → capture all errors
- Categorize errors (auto-fixable vs. manual)
- Apply automated fixes where possible:
# Use codemods for common patterns
npx ts-migrate -e noImplicitAny src/
# Or custom jscodeshift transforms
- Manual fixes for complex cases (add to tech debt backlog if needed)
- Run tests → ensure no behavioral changes
- Update metrics → commit with message:
feat(types): enable [flag] - 234 errors fixed
metrics: type-coverage 87% → 92%
Exception Handling:
// Use sparingly with documentation
// @ts-expect-error: [JIRA-123] Legacy API returns mixed type
const data = unsafeApiCall();
// Or for unavoidable cases:
/* eslint-disable @typescript-eslint/no-explicit-any */
(window as any).legacyLib = value;
Phase 6: Automation Script
Create scripts/strictness-ratchet.js:
const FLAG_GROUPS = [
['noImplicitAny'],
['strictNullChecks', 'noImplicitThis'],
['strictFunctionTypes', 'strictBindCallApply'],
['strictPropertyInitialization'],
['noImplicitReturns', 'noFallthroughCasesInSwitch'],
['exactOptionalPropertyTypes', 'noImplicitOverride'],
['noUnusedLocals', 'noUnusedParameters']
];
async function ratchet() {
for (const group of FLAG_GROUPS) {
console.log(`\n=== Enabling: ${group.join(', ')} ===`);
// 1. Enable flags
enableFlags(group);
// 2. Run compiler
const errors = await runTsc();
// 3. Apply automated fixes
await applyCodemods(group);
// 4. Manual review for remaining errors
const remaining = await runTsc();
if (remaining > 0) {
console.log(`Remaining ${remaining} errors need manual review`);
generateErrorReport();
}
// 5. Run tests
await runTests();
// 6. Update metrics
updateMetrics();
// 7. Commit
gitCommit(`chore: enable ${group.join(' ')}`);
}
}
Phase 7: CI/CD Integration
# .github/workflows/strictness.yml
name: TypeScript Strictness
on:
push:
paths: ['tsconfig.json', 'src/**']
jobs:
check-strictness:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: npx tsc --noEmit
# Fail on any type error
- run: npx type-coverage --strict --at-least 95 src/
- run: npx madge --image graph.svg src/ # Detect circular deps
- uses: actions/upload-artifact@v3
with:
name: strictness-metrics
path: metrics.jsonl
Phase 8: Monitoring & Governance
Monthly Safety Report:
## TypeScript Safety Metrics - $MONTH
| Metric | Current | Change |
|--------|---------|--------|
| Strict Flags | 9/14 | +2 |
| Type Coverage | 94.2% | +1.1% |
| `any` Usage | 12 | -8 |
| Avg Cyclomatic | 4.2 | -0.3 |
| Test Coverage | 87% | +2% |
### Top Violations:
1. `strictNullChecks` - 23 locations (mostly legacy APIs)
2. `noUnusedLocals` - 17 parameters (debug code)
### Action Items:
- [ ] Fix legacy API wrappers (JIRA-456)
- [ ] Remove debug code in `utils/debug.ts`
Enforcement Rules:
- No new
any - CI fails on implicit/explicit any in new code
- No flag regression - Once enabled, never disabled
- Gradual migration - Max 1 flag group per sprint
- Tech debt tracking -
// TODO-TS-STRICT: comments require tickets
Phase 9: Advanced Metrics
Track these additional signals:
// In your metrics script:
const advancedMetrics = {
// Type safety
unknownUsage: count('unknown'), // Should increase with useUnknownInCatchVariables
nonNullableAssertions: count('!'), // Track definite assignment assertions
// Design quality
interfaceSegregation: count('interface'), // vs type aliases
discriminant Unions: count('|') & hasLiteral(), // Proper discriminated unions
genericDepth: analyzeGenericDepth(), // Prevent overly complex generics
// Migration progress
migrationCoverage: {
legacyApi: count('LegacyApi'),
unsafeCast: count('as any'),
tsIgnore: count('@ts-ignore')
}
};
Rollback Strategy
- Feature flags for critical paths during migration:
// config/strictness.ts
export const STRICT_NULL_CHECKS = process.env.NODE_ENV === 'production';
- Gradual file enablement using
// @ts-strict comments:
// @ts-strict: strictNullChecks
// File enables extra checks
- Canary builds deploy to 5% traffic first
Success Criteria
- ✅ All 14 strict flags enabled
- ✅ Type coverage ≥ 95%
- ✅
any usage ≤ 5 instances (only in boundary code)
- ✅ 0 new
@ts-ignore comments
- ✅ 80%+ codebase with ≥ 90% type coverage per file
- ✅ Cyclomatic complexity ≤ 10 per function (avg)
This ratchet balances safety with pragmatism. Each phase delivers measurable improvements while maintaining deployability. The key is consistent metrics tracking and never reversing progress.