Skip to main content

01 - Strict Mode Is Not Enough: 100 Type Breaches in a 100% Strict TypeScript Monorepo

Measured on 31 October 2026: 54 'as any' casts, 50 in tests and one false positive. Three remain in production, and only one needs fixing.

What do you think about this article?

01 - Strict Mode Is Not Enough: 100 Type Breaches in a 100% Strict TypeScript Monorepo
TypeScript Avanzatofedericocalo.dev

At a Glance

Measured on 31 October 2026: 54 'as any' casts, 50 in tests and one false positive. Three remain in production, and only one needs fixing.

Direct answer

In this monorepo the tsconfig file has strict, strictTemplates and strictInjectionParameters all switched on, and on 31 October 2026 there are still 60 occurrences of ': any' and 54 of 'as any' across 4293 TypeScript files. The interesting figure is not the total: 50 of the 54 casts sit in test files, and of the 4 that remain, one is a false positive of the grep. In production the real casts are three. Strict mode closes the accidental errors, not the deliberate escape hatches.

"I have strict: true, so my code is type-safe" is a sentence you hear often and rarely see checked on a project of real size. If you are saying it about yours, this article suggests you stop arguing about it and count it, with four commands you can run right now on your own repository. I ran them on mine, and the result changed my mind about what the problem actually is.

Strict mode is necessary and not sufficient, and so far that is a commonplace. The part that is always skipped is the second question: if the escape hatches remain, where do they end up? The answer measured on this project is not the one I expected, and it completely changes the kind of intervention that makes sense.

What strict closes, and what stays open

The strict flag is not a check: it is a switch that turns other checks on. How many, you do not need to remember, because the compiler tells you: npx tsc -p tsconfig.app.json --showConfig prints the configuration with all the implicit values resolved. On this project, with TypeScript 5.9, the sub-flags that get switched on are nine, and it is worth reading them because each one closes a different category of trouble.

  • noImplicitAny: forbids the compiler from inferring any when it cannot work out a type, and turns it into an error.
  • strictNullChecks: removes null and undefined from the domain of every type, forcing you to declare them where they are possible.
  • strictFunctionTypes: checks the compatibility of function parameters contravariantly, that is, in the direction that is actually safe.
  • strictPropertyInitialization: demands that every non-optional class property be assigned in the constructor.
  • strictBindCallApply: checks the types of the arguments passed through bind, call and apply.
  • useUnknownInCatchVariables: types the catch variable as unknown instead of any, which is why you write err instanceof Error on an error.
  • noImplicitThis, alwaysStrict and strictBuiltinIteratorReturn: respectively the untyped this, JavaScript's strict mode always on, and the return types of the built-in iterators.

To these nine the project adds two checks that come from the Angular compiler: strictTemplates, which extends type checking inside HTML templates, and strictInjectionParameters, which extends it to the parameters injected into constructors.

Everything this package catches has one property in common: nobody wrote it on purpose. A variable that becomes any because the compiler cannot infer it, an access to a property of an object that may be null, a parameter forgotten in a subclass. These are faults born from the absence of a constraint, and a constraint eliminates them.

What stays outside is everything deliberate, and there are three forms, in order of how hard they are to find. The first is any written by hand, which is honest because it is visible. The second is the as cast, which is worse because it asserts a type that the compiler accepts without checking. The third is the @ts-expect-error comment, which switches the check off on a single line. No flag can close these three roads, because they are exactly the relief valves that make TypeScript adoptable on code that already exists.

The count, with the commands to redo it

The numbers that follow come from four commands run from the frontend/ folder on 31 October 2026. They are not an estimate and they do not come from an analysis tool: they are counts of textual occurrences, with all the limits that implies, and which in a moment become the central point of the article.

Escape hatches from the types, measured on 31 October 2026 on src/app

Command Result In test files Outside tests
grep -ro ': any\b' src/app | wc -l 60 27 lines 32 lines
grep -ro 'as any\b' src/app | wc -l 54 50 lines 4 lines
grep -rn '@ts-expect-error' src | wc -l 6 6 lines 0
find src/app -name '*.ts' | wc -l 4293 1941 files 2352 files

The row that matters is the second. Fifty casts out of fifty-four sit inside files ending in .spec.ts, that is, inside the tests. And all six of the project's @ts-expect-error comments are there too. The distribution is not uniform: it is concentrated in one place, and that place has different rules.

The grep that lies, and why it is the most useful part of this article

Before explaining the four casts outside the tests, it is worth actually looking at them, because counting them is not enough. Running the command and reading the four lines one by one, the fourth is this:

The fourth occurrence, read instead of counted

src/app/data/learning-paths-sections-ai-security.ts:175 contains the text "Generated text ending up in a page, a query, a shell command or an HTTP call: the same rules as any external input, from escaping to parameterisation."

That is not a cast. It is English prose inside a string, where as any means "like any". My command counted it because it searches for two words, not for a language construct. So the real casts in production code are three, not four, and the headline I had in mind for this article was wrong by 25 per cent on a base of four.

The lesson is not about any: it is about the method. A count obtained by searching for a bare token measures the token, not the meaning, and the difference grows with the size of the project. If a number like that has to end up in a decision, in a review or in an article, you read the occurrences one by one while they are few, and you use a tool that understands the syntax when they become many. The practical rule I took from it is that a grep is fine for knowing whether it is worth looking, and not fine for saying how many.

The three real casts, one by one

Three cases in two thousand three hundred and fifty-two files are not an alarm. They are, however, a perfect sample, because they are three casts written for three different reasons, and they deserve three different verdicts.

The cast that declares a known hole

In progetto-dashboard.ts a line reads a charting library from a global variable, with (window as any)['echarts'], and above it there is a comment explaining that the library is loaded lazily and registers itself on the global object. This cast is defensible: it says something true, namely that at that point the type is not known, and it says it out loud.

It is defensible and it can be done better, because the type is not unknown: it is only not declared. What you need is not the complete typing of the library, but the small piece you actually use.


// The minimum that is really needed from echarts, not its full typing.
interface EchartsGlobale {
  init(
    contenitore: HTMLElement,
    tema?: string,
    opzioni?: { renderer: 'canvas' | 'svg'; locale: string },
  ): { setOption(opzioni: unknown): void };
}

declare global {
  interface Window {
    echarts?: EchartsGlobale;
  }
}

export function prendiEcharts(): EchartsGlobale | undefined {
  // No cast: 'echarts' now exists in the Window type, and it may be absent.
  return window.echarts;
}
      

Two things need explaining here, because they are the two you will use. declare global opens a declaration in the global namespace from inside a module: without it, the Window interface you write would stay local to the file and would not merge with the one in the standard library. The merge works because TypeScript interfaces are open, that is, two declarations with the same name add up instead of conflicting. The question mark in echarts? is the other half: it declares the property as possibly absent, and with strictNullChecks on this forces whoever reads it to handle the case in which the library has not arrived yet. Leaving it out produces a type that promises a presence that lazy loading does not guarantee, and moves the failure from a compiler check to a blank-screen error.

This block compiles with the flags of this project, verified with the repository's compiler. The price of this road is that the interface you wrote is a claim of yours: if the library changes the signature of init, the compiler will keep agreeing with you and being wrong. It is called hearsay typing, and it is still better than any, because a written claim can be reread and corrected, while any claims nothing.

The interoperability cast

In qr-code-generator-page.ts the cast solves an old problem: a dynamically imported module can expose its function as default or directly, depending on how it was packaged, and the line (mod as any).default || mod covers both cases. It looks like the cast with the soundest justification of the three, because the shape of the value depends on the packaging of the package and not on the code that uses it.

The clean road is not a better type: it is a compiler option. esModuleInterop normalises exactly this difference between the two packagings and makes the line unnecessary. And here the check gives an outcome I did not expect: the same --showConfig command as before reports esModuleInterop: true on this project, because the module: preserve option implies it. The option was already on before the cast was written.

So the verdict on this second case changes while you look at it: it is not the cast with the soundest justification, it is a cast that is not needed. It defended against a problem the configuration had already solved, and nobody reopened it because a cast produces no signal when it becomes superfluous. That is why it pays to write next to every escape hatch not only the reason, but also the condition that would make it removable.

The cast that asserts something false

The third is the only one I consider a defect, and it is in audit-page.ts. The call declares to the compiler that the response has two fields, and then the code reads a third.


// The contract declared at the call: two fields, no error.
interface AvvioAudit {
  runId: string;
  status: string;
}

declare function post<T>(url: string, body: unknown): Promise<{ data: T | null }>;

export async function avvia(url: string): Promise<string> {
  const risposta = await post<AvvioAudit>('/audit/run', { url });
  if (risposta.data?.runId) {
    return risposta.data.runId;
  }
  // 'error' does not exist in AvvioAudit: the cast makes it exist for show.
  throw new Error((risposta.data as any)?.error ?? 'Errore avvio audit');
}
      

Remove the cast, and the repository's compiler says exactly this:


03-senza-cast.ts(13,34): error TS2339: Property 'error' does not exist on type 'AvvioAudit'.
      

The error is correct and the cast silences it without answering it. The point is not stylistic: that cast asserts the field exists, and if the server stops sending it the line produces undefined, the fallback operator returns the generic message, and the real reason for the error disappears exactly where it was needed. The declared type and the real contract do not coincide, and the cast exists so that nobody notices.

The fix is not to replace any with unknown: it is to tell the truth about the contract. A response that can be a success or an error is not an object with optional fields, it is two alternative shapes, and the type that expresses them is a discriminated union.


// The real contract has two alternative shapes, and the type says so.
type EsitoAudit =
  | { ok: true; runId: string; status: string }
  | { ok: false; error: string };

declare function post<T>(url: string, body: unknown): Promise<{ data: T | null }>;

export async function avvia(url: string): Promise<string> {
  const risposta = await post<EsitoAudit>('/audit/run', { url });
  const esito = risposta.data;
  if (esito === null) {
    throw new Error('Risposta vuota dal server');
  }
  if (esito.ok) {
    return esito.runId;
  }
  // Here the compiler knows 'error' exists, with no cast at all.
  throw new Error(esito.error);
}
      

The ok field is the discriminant: a literal value, different in the two branches, which the compiler uses to work out which branch it is in. After if (esito.ok) the type of esito inside the block is only the first branch, so runId is readable and error does not exist; in the else branch the opposite holds. There is no cast, and neither of the two accesses can go wrong. The separate check on null at the start is there because the response type allows for the absence of a body, which is a third case and must not be confused with the application error.

This version has a price too, and it needs saying: the type has to match what the server really sends. If you write it by looking at the client code instead of the contract, you have moved the lie from the cast to the type, which is a place where it is less visible. What made the difference, in my case, was opening the controller that answers that call and reading the two shapes it produces.

Fifty casts in the tests: the same construct, a different rule

What remains is the concentration the count brought out, and it is the part really worth taking away. In tests the cast almost always serves one thing only: reaching a private member or replacing a dependency with a fake object that does not implement the whole interface. It is a different use, with a different risk.

A cast in production code hides a wrong contract, and a user pays the price. A cast in a test hides at most a fragile test, and the price is paid by whoever does the next rename, discovering that the test keeps passing while it checks a method that no longer exists. The damage is real but of a different order of magnitude, and that is why a lint rule that treats the two cases the same way gets switched off within a week.

The practical consequence is that the sensible intervention on this project is not a campaign to zero out any. Three production casts do not justify a campaign, and I fixed only one of them because it was the only one that said something false. What is needed is a rule that tells the two contexts apart: strict where the code goes into service, tolerant where a test double lives.

What I would do now, in order of return

These four things can be done independently, in any order, and each one can be checked on its own.

  • Enable @typescript-eslint/no-explicit-any as a warning and not as an error, with a separate configuration for the *.spec.ts files: severity goes where the code is run by users.
  • Demand a comment on every escape hatch that remains, with the reason and the date: the echarts cast in this project has one, and that is why it was the easiest of the three to assess.
  • Prefer @ts-expect-error to @ts-ignore: the former becomes an error itself when the line underneath stops being wrong, so it cleans itself up. Here the @ts-ignore comments number zero, and it is the only figure in this measurement that pleased me.
  • Count periodically, and read the occurrences while they are few: the number alone would have kept in the article a false positive and three indistinguishable cases.

The four points do not ask for the same effort nor pay off in the same way: the first changes where severity falls and therefore the number of reports someone will actually read, the second and the third cost one line per escape hatch, the fourth is a routine that finds drift before it becomes habit. If you pick only one, pick the first, because without a rule that separates production from tests the other three produce noise.

Closing

You now have four commands to measure the escape hatches from the types on your own project, and a reason not to trust the total they return: out of four occurrences outside the tests, one was English prose. You can tell apart the three cases that matter, namely the cast that declares a known hole, the one that covers a packaging difference and the one that asserts a field that does not exist, and you know that only the third needs fixing.

You also know how to fix it, because the block with the discriminated union above compiles with the same flags as this repository, and the error the compiler emits without the cast is reported in full. The next article in the series picks up where this one stops: the boundary where data enters the program, and the difference between any and unknown when you do not yet know what shape the data has.

Frequently asked questions

What does TypeScript's strict flag actually turn on?

In version 5.9 it turns on nine distinct checks, among them noImplicitAny, which forbids the compiler from inferring any when it cannot work out a type, and strictNullChecks, which removes null and undefined from the domain of types. They eliminate accidental errors, not the escape hatches written on purpose.

Is an 'as' cast worse than a declared any?

Usually yes, because it asserts a type that the compiler accepts without checking, while any asserts nothing. A cast that declares a field the response does not have is a lie that the next reader will take as a guarantee.

How many any are there really in this project?

On 31 October 2026, on src/app: 60 occurrences of : any and 54 of as any across 4293 TypeScript files. Of the 54 casts, 50 are in test files and 4 outside, but one of the four is a false positive of the grep, because it is English prose in which as any means "like any". The real production casts are three.

Why is counting with grep not enough?

Because it searches for a token and not for a language construct, so it also counts occurrences inside strings and comments. On a base of four cases, a single false positive moves the result by 25 per cent. A grep is fine for deciding whether it is worth looking, not for saying how many.

Is it worth zeroing out all the remaining any?

No, and not out of laziness: it is better to tell the contexts apart. A cast in production hides a wrong contract and a user pays for it; a cast in a test hides at most a fragile test. A rule that treats the two cases the same way gets switched off within a week.

The same series also includes Type guards, Discriminated unions, satisfies and the keys of a catalog and Template literal types.

Sources and further reading

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects