Sub topic 9
Containing any: lint rules and migration strategy
This chapter covers how any enters a codebase, how to stop it spreading, and how to remove it from an existing project step by step. It assumes you can read tsconfig.json, run tsc, and have used unknown and type guards from the earlier chapters. You should also know how to install an npm dev dependency and edit a config file.
Why any needs containment, not just avoidance
Banning the word any from your source does not keep any out of your program. Most any values come from code you did not write, and one any can spread through everything it touches.
Common sources:
JSON.parsereturnsany.Response.json()in thefetchAPI returnsPromise<any>.- Older or sloppy third-party type declarations use
anyin their signatures. - A module with no types can be declared as
declare module "legacy-lib";. After that, everything imported from it isany. - An empty array literal such as
const xs = [];starts as an evolvingany[]whennoImplicitAnyis off. - Parameters without annotations are implicitly
anywhennoImplicitAnyis off.
The spreading is the real problem. When you read a property from an any, call it, or pass it along, the result is also any.
function loadConfig(text: string) {
const cfg = JSON.parse(text); // any
return cfg; // inferred return type: any
}
const port = loadConfig('{"port":8080}').port; // any
const doubled = port * 2; // number, but only by luck
const label = port.toUpperCase(); // compiles, throws at runtimeloadConfig has no annotations that mention any, yet every caller receives an unchecked value. The any stays hidden in the inferred return type.
The containment principle
Stop any at the boundary where it enters. Do this by giving the value a safe type immediately, before any other code can use it.
function parseJson(text: string): unknown {
return JSON.parse(text);
}
interface Config {
port: number;
}
function isConfig(value: unknown): value is Config {
return (
typeof value === "object" &&
value !== null &&
"port" in value &&
typeof value.port === "number"
);
}
function loadConfig(text: string): Config {
const parsed = parseJson(text);
if (!isConfig(parsed)) {
throw new Error("Invalid config: expected an object with a numeric port");
}
return parsed;
}
console.log(loadConfig('{"port":8080}').port * 2); // 16parseJson is the only place that touches JSON.parse. Its return type is unknown, so the compiler forces the validation in loadConfig. The in narrowing on value.port needs TypeScript 4.9 or later.
Return types are the best place to contain any. If a function has an explicit return type, an any inside its body cannot leak out through inference. Assigning an any to a variable annotated unknown or to a specific type also stops it, because any is assignable to every type.
Compiler options that expose any
Two options in tsconfig.json do most of the work. Both are part of "strict": true.
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"useUnknownInCatchVariables": true
}
}noImplicitAnyreports an error wherever TypeScript would have to inferanybecause it has no information, such as an unannotated parameter.useUnknownInCatchVariablestypescatch (err)asunknowninstead ofany.
These options only catch implicit any. They say nothing about any that you write explicitly, and nothing about any that arrives from JSON.parse or a library. The compiler treats those as deliberate. This is why you also need lint rules.
Lint rules that block any
The typescript-eslint project provides rules that cover each way any can travel. The rules marked "type-aware" need type information, so ESLint must be able to load your tsconfig.json.
| Rule | What it reports | Type-aware |
|---|---|---|
| `no-explicit-any` | The `any` keyword written in a type annotation | No |
| `no-unsafe-assignment` | Assigning an `any` value to a variable or property | Yes |
| `no-unsafe-member-access` | Reading a property of an `any` value | Yes |
| `no-unsafe-call` | Calling an `any` value as a function | Yes |
| `no-unsafe-argument` | Passing an `any` value as an argument to a typed parameter | Yes |
| `no-unsafe-return` | Returning an `any` value from a function | Yes |
no-explicit-any catches what you type. The no-unsafe-* rules catch what flows in from elsewhere, including the JSON.parse result in our first example. Running no-explicit-any alone gives a false sense of safety.
The easiest setup is a preset. The strictTypeChecked preset includes all of these rules. This is an eslint.config.mjs using the flat config format:
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
export default tseslint.config(
eslint.configs.recommended,
tseslint.configs.strictTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
);import.meta.dirname requires Node.js 20.11 or later. On older versions, compute the directory with path.dirname(fileURLToPath(import.meta.url)).
Install the packages with npm install --save-dev eslint @eslint/js typescript-eslint. Then run npx eslint . and your CI can fail the build on errors.
Typing an unavoidable any
Sometimes any is the correct type. A generic higher-order function that must accept any function signature is one example, because unknown[] parameters are too narrow for contravariant positions.
function logged<TArgs extends any[], TResult>(
fn: (...args: TArgs) => TResult,
): (...args: TArgs) => TResult {
return (...args) => {
console.log("calling with", args);
return fn(...args);
};
}
const add = logged((a: number, b: number) => a + b);
console.log(add(2, 3)); // 5, and add still has typed parametersHere the any[] constraint never leaks. Callers see [a: number, b: number]. When you keep an any like this, disable the rule on that line only and write the reason:
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any parameter list
function logged<TArgs extends any[], TResult>(A disable comment with a reason is searchable and reviewable. A silent any is neither.
Suppressing compiler errors without creating any
During a migration you will meet errors you cannot fix right away. Use // @ts-expect-error rather than // @ts-ignore or a cast to any.
const settings: { retries: number } = { retries: 3 };
// @ts-expect-error legacy callers pass a string; remove after the v2 API lands
settings.retries = "3";@ts-expect-error reports an error when the line below it no longer has a problem. A stale suppression therefore cannot hide in the code. @ts-ignore stays silent forever.
A migration strategy for an existing codebase
Turning on every rule at once in a large project produces thousands of errors, and teams often give up. A staged approach works better. Each stage ends with a green build, so you can stop between stages.
- Enable
noImplicitAny. Fix the errors by annotating parameters and returns. If the count is too large, fix one directory at a time using a separatetsconfig.strict.jsonthat extends the main file and lists only the finished directories ininclude. - Wrap the boundaries. Find every
JSON.parse,response.json(),localStorageread, and untyped import. Put each behind one small function that returnsunknownor a validated type, likeparseJsonabove. This is usually a few dozen call sites, not thousands. - Turn on the lint rules in stages. Set
no-explicit-anyand theno-unsafe-*rules towarnfor the whole project, anderrorfor new or already-clean directories. ESLint'soverridesthroughfilespatterns support this. - Ratchet. Record the current number of warnings. Fail CI if the count rises. As files get fixed, lower the limit. ESLint supports this with
--max-warnings <count>.
For stage 3, a flat config can scope severity by path:
export default tseslint.config(
tseslint.configs.strictTypeChecked,
{
languageOptions: {
parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname },
},
},
{
files: ["src/legacy/**/*.ts"],
rules: {
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-unsafe-assignment": "warn",
"@typescript-eslint/no-unsafe-member-access": "warn",
"@typescript-eslint/no-unsafe-call": "warn",
"@typescript-eslint/no-unsafe-argument": "warn",
"@typescript-eslint/no-unsafe-return": "warn",
},
},
);Files under src/legacy report warnings, and the rest of the project gets errors.
Measuring progress
A lint warning count is a good proxy. For a direct measure, the third-party type-coverage tool reports the percentage of identifiers whose type is not any. Run npx type-coverage --at-least 95 in CI to fail when coverage drops below a threshold. Raise the threshold as you improve.
Gotchas
declare module "x";turns the whole module intoany. Replace it with a real declaration file, or install@types/x. If you need a stopgap, declare only the functions you use with real types.skipLibCheckhides errors in.d.tsfiles. It is normal to enable it, but remember that a library's ownanycan still reach your code through its signatures.- Casting to
anyto silence an error spreads the error. Cast to the narrowest type that fixes the problem, or tounknownfollowed by a guard. - Generic defaults can be
any. Some APIs, such asPromise<any>fromfetch, or an event emitter without type parameters, give youanyunless you supply a type argument. - Lint rules are not free. Type-aware rules make ESLint slower because it runs the type checker. Limit them to
srcand exclude generated files.
Exercise
Your team enabled "strict": true, yet the line const data = await (await fetch(url)).json(); still produces an any that flows into later code. Name the compiler-level reason, and give one fix at the boundary and one lint rule that would have caught it.
Show answer
The compiler allows it because strict only reports implicit any from missing information. Here Response.json() is declared to return Promise<any>, so the any is explicit in the library's types. The fix at the boundary is to annotate the result as unknown (const data: unknown = await response.json();) or wrap the call in a function that returns unknown or a validated type, then narrow with a type guard. The rule @typescript-eslint/no-unsafe-assignment reports assigning the any result to a variable. no-unsafe-member-access would report later reads of its properties.
Exercise
Why is // @ts-expect-error preferred over // @ts-ignore during a migration?
Show answer
@ts-expect-error itself reports an error once the line below no longer has a type error, so you are forced to delete the stale comment. @ts-ignore suppresses errors silently and indefinitely, which lets real problems hide as the code changes.