Stop drowning in any: turning on strict mode for AI-generated TypeScript
AI-generated TypeScript that runs with zero errors may only mean type checking was never on. This guide follows the official TypeScript Handbook through the strict master switch, the cost of any, strictNullChecks, union narrowing, literal types with as const, and assertion boundaries, with a five-step rollout.

First, the boundaries. This guide is only about types — not testing, not builds, not upgrades. This site already has guides on AI testing strategy, end-to-end testing, and test-double strategy for how to write tests, and a major-upgrade checklist for how to upgrade frameworks. None of them is about the type layer. This guide is about one earlier step: AI generated a pile of TypeScript code for you, it runs fine, and the compiler reports no errors — but you know in your gut it only runs because type checking was never really turned on. The job is not to rewrite the code. It is to switch on TypeScript's own strict mode and let the compiler report the problems it has been hiding.
The "Recipe House" used below is a fictional practice project: a small app that stores recipes, totals them by category, and reminds the user to buy missing ingredients. Every action, code snippet, and number built around it in this article was invented to explain the method. It is not a real record. All facts about TypeScript types, compiler options, and behavior come from the official TypeScript Handbook and the official tsconfig reference; the sources are in each article's meta information and evidence record. The Oby and Heera example in the Handbook is the documentation's own example, not real users.
What strict is: one switch for a whole set of checks
The official TypeScript documentation defines strict in a single sentence: turning it on enables a wide range of type checking behavior that results in stronger guarantees of program correctness. It is not one check but a master switch for a family of checks. Turning on strict is equivalent to turning on every option in the strict family, and afterwards you can switch off individual ones as needed. The documentation adds a sentence that is easy to miss: future versions of TypeScript may introduce additional stricter checking under this flag, so upgrading TypeScript may produce new type errors in your program. That is not the upgrade breaking your code — the checks got stricter, and the problems they report were there all along.
For vibe coding, the practical meaning of that master switch is simple. AI-generated code often ships with strict off by default — because with strict off, code is more likely to "pass on the first try." The "zero errors" you see may mean the code is genuinely fine, or it may mean the checks were never on. The right way to turn it on is the other way around: switch everything on first, see how many errors appear, then fix them one by one; only switch off a specific rule you genuinely cannot fix, and write in a comment why it is off. On-first-then-off versus off-first-then-on differ only in order, but the outcomes are worlds apart: the first means you actively choose what to let slide, the second means you never knew what you let slide.
If you are taking over a long-lived project, switching everything on at once may produce hundreds of errors. Do not panic — that is normal. The right approach is two steps: first turn on only strictNullChecks and noImplicitAny, the two most valuable rules, fix those, and then switch on the full set. Walking in stages is not laziness; it turns the error list from "unreadable" into "fixable one at a time."
The cost of any: switch the checks off and everything passes
The TypeScript Handbook defines any bluntly: when a value is of type any, you can access any of its properties, call it like a function, assign it to or from a value of any type, or pretty much anything else that is syntactically legal. Its example pulls no punches: let obj: any = { x: 0 }, then obj.foo(), obj(), obj.bar = 100, obj = "hello", and const n: number = obj — not one line throws a compiler error. The Handbook's own words are that using any disables all further type checking, and it is assumed you know the environment better than TypeScript. AI-generated code loves exactly this: faced with data of unknown type, it writes any, the compiler goes quiet at once, and the problem is hidden at once.
More hidden than an explicit any is an implicit any: you wrote no type, TypeScript cannot infer one either, and it quietly defaults to any. The Handbook covers this directly: when you do not specify a type and TypeScript cannot infer it from context, the compiler will typically default to any — and you usually want to avoid this, because any is not type-checked. The fix is the noImplicitAny compiler flag, which turns every implicit any into an error. In AI-generated code, implicit any shows up most often in three places: callback parameters with no type annotation, the return value of JSON.parse used directly, and objects from third-party libraries with no declared type. All three look runnable and hide landmines, and noImplicitAny exists to light them up.
Two easily confused concepts need separating here: any and unknown. any means "stop checking, I want it all"; unknown means "do not trust it yet, check it first." Data from AI-generated interfaces, user input, or localStorage should start as unknown, then be narrowed to a concrete type with typeof or in — much safer than writing any directly. any is not forbidden; its legitimate place is "you genuinely know the runtime better than the compiler, and only in a very small area," for example a temporary bridge for a third-party library's return value. The test is simple: if one any is still in effect more than three lines later, it is not a bridge — it is a leak.

strictNullChecks: admit first that things may not exist
JavaScript has two primitive values for "absent": null and undefined. With strictNullChecks off, the language effectively ignores both — any type of value may be null, and you can write code as if they did not exist. The Handbook says plainly that this can lead to unexpected errors at runtime. With the option on, null and undefined have their own distinct types, and the compiler reports an error if you try to use them where a concrete value is expected. The Handbook's recommendation is equally plain: it always recommends turning strictNullChecks on if it is practical to do so in your codebase.
The official example is worth reading as written. There are two users, Oby and Heera, and the code uses users.find to look up the logged-in user, then reads loggedInUser.age directly. find carries no guarantee it will actually find a user, but with the checks off, you can write code as though it will. With strictNullChecks on, the compiler reports an error at once: 'loggedInUser' is possibly 'undefined'. The Handbook even shows you find's simplified type: with the check on, find returns S | undefined; with it off, that undefined is removed from the type system. In other words, switching the check off does not make "user not found" go away — it only makes the compiler pretend it cannot happen.
There are three fixes, all written in the Handbook. The first is to check before using: if (x === null), handle the absent case first, and in the else branch x is definitely not null. The second is optional chaining ?. and nullish coalescing ??: obj.last?.toUpperCase() returns undefined when there is no last instead of crashing, and ?? supplies a default when the value is absent. The third is the non-null assertion !, written after an expression to mean "I guarantee this is not null or undefined." The Handbook's warning about this one is strict: it does not change the runtime behavior of your code, so only use ! when you know the value cannot be null or undefined. AI-generated code loves writing ! everywhere, because one exclamation mark is easier than a null check. The first job when taking such code over is to replace every ! with a real check.
Union types and narrowing: figure out which one it is first
A union type means "it may be this, or it may be that": number | string says a value may be a number or a string. The Handbook's rule is practical: if you have a value of a union type, TypeScript will only allow an operation if it is valid for every member of the union. For string | number, you cannot call toUpperCase directly, because that method only works on the string member, not the number. The solution is narrowing: shrink the range with code, the same as you would in JavaScript without type annotations.
The Handbook gives two most common narrowing techniques. The first is typeof: inside if (typeof id === "string"), id is a string and you can safely call toUpperCase; in the else branch, id must be a number. The second is Array.isArray: for a value that may be string[] or string, Array.isArray(x) tells you that inside the branch x is string[] and you can call join directly, while in the else branch x is a string. Narrowing is not an advanced trick. It is "check first, then use" — except the compiler gets smarter along with your check.
The most common AI mistake here is skipping the narrowing and calling methods directly. The classic case: an API returns data that may be an object or null, and the code reads a field without checking; or a function parameter is string | string[], and the code calls .join directly, crashing the moment a string arrives. Under strict mode, this code fails at compile time, which turns "the user discovers it first" into "the compiler discovers it first." When fixing it, remember the order: narrow first, then use — never the reverse. And keep the narrowing check close to where the value is used; ten lines apart, neither humans nor the compiler can follow it.
Literal types and as const: write "only these values" into the type
Beyond broad types like string and number, TypeScript can treat one specific value as a type. A variable declared with let can change, so its type is string; a variable declared with const cannot change, so its type is exactly that one string, such as "Hello World." A single literal type on its own is not very useful — a variable that can only be "hello" is not much use. But combined into unions, literals express a much more useful concept: a function that only accepts a certain set of known values, for example alignment: "left" | "right" | "center". Pass "centre" and the compiler reports an error at once — a typo caught at compile time instead of by a user noticing crooked layout.
There is a trap here that shows up constantly in AI-generated code, and the Handbook covers it specifically. Suppose you call handleRequest(url: string, method: "GET" | "POST"), starting with const req = { url: "https://example.com", method: "GET" } and then calling handleRequest(req.url, req.method). The compiler reports an error: req.method has type string, not "GET." Why? Because TypeScript reasons that between creating req and calling the function, code could assign another string — such as "GUESS" — to req.method, so it can only infer the broad type string. The Handbook gives two workarounds: either assert at creation time with method: "GET" as "GET", meaning "I intend for this to always have the literal type," or add as const to the whole object, meaning "treat the entire object like const," so every property takes its literal type. The second is less work: lock the object once, and every value inside becomes unchangeable and tightly typed.
Literal unions fit best in three places: status fields ("draft" | "published" | "archived"), HTTP methods ("GET" | "POST"), and component sizes or alignments. AI-generated code likes to write these as broad strings, and a misspelled letter passes the compiler silently. With a literal union, misspellings, wrong values, and case errors all surface at compile time. The cost is exactly one thing: adding a new legal value means changing the type definition — which is precisely what you want, because adding a new status should be visible everywhere it is used.
Type assertions and non-null assertions: an escape hatch, not the front door
Sometimes you genuinely know more about a value's type than the compiler does. The Handbook's canonical example is document.getElementById: TypeScript only knows it returns some kind of HTMLElement, but you know the element with that id is always a canvas. Then you can use a type assertion — as HTMLCanvasElement — to specify a more specific type. The Handbook warns about two things: first, assertions are removed by the compiler and will not affect runtime behavior; second, if the assertion is wrong there will be no exception and no null generated — wrong is just wrong, and it still crashes at runtime.
Assertions have one iron rule: TypeScript only allows assertions that convert to a more specific or less specific version of a type, never an "impossible" conversion. The Handbook's example is const x = "hello" as number, which the compiler rejects because neither type sufficiently overlaps with the other; if that was intentional, convert to unknown first. AI-generated code frequently uses the double assertion as any as T: convert to any first to wash everything away, then to the desired type. The Handbook admits this can bypass an overly conservative check, but it should be treated as an escape hatch, not the front door — two double assertions in one file mean the type design itself is wrong. Fix the types first, then talk about assertions.
The non-null assertion ! is the same idea in another form: written after an expression, it asserts that the value is not null or undefined. It likewise does not change runtime behavior. There is only one test for whether a ! should stay: can you explain in one sentence why it cannot be empty? If you can, keep it, and ideally write that sentence as a comment. If you cannot, replace it with a real null check. In the fictional Recipe House project, 12 of the 240 errors after switching on strict mode were assertion abuse, and the fix was identical every time: delete the !, add the check, and the error disappeared — because the error was never the compiler being difficult. The code genuinely had not handled the "absent" case.
type versus interface: tell them apart, then pick a side
TypeScript offers two ways to name a type: type aliases and interface declarations. They are very similar, and in many cases you can choose freely. The Handbook lays out the key distinction in a comparison table: an interface can be extended with extends and can gain new fields by declaring the same interface name again; a type extends through intersections such as Animal & { honey: boolean }, and once created it cannot be changed — declaring the same type twice is a duplicate-identifier error. The Handbook lists further fine differences: interface names always appear in error messages in their original form, while type alias names may be replaced by the equivalent anonymous type in versions before 4.2; interfaces can participate in declaration merging but types cannot; interfaces may only declare the shapes of objects, not rename primitives; and interfaces with extends can often be more performant for the compiler than types with intersections.
The Handbook's advice is simple: use interface until you need to use features from type. AI-generated code often does the opposite, with type everywhere because it writes smoothly. A workable rule of thumb: use interface to describe "what something looks like," and type for "combinations of types" — unions, intersections, mapped types. Another practical split: use interface for outward-facing shapes such as data structures returned by the backend or component props, keeping them extendable; use type for temporary combinations assembled internally. When in doubt, do not agonize — the error messages will tell you, because the compiler reports clearly when it needs the other kind of declaration.
Five steps to land it: from 240 errors to zero
Step one: turn on strictNullChecks and noImplicitAny first, fix those, then switch on the full strict set. The point of staging is to turn the error list from "unreadable" into "fixable one at a time." The fictional Recipe House project did exactly this: the first two rules produced 174 errors; fixing those and switching on the full set added 66 more, for 240 in total.
Step two: fix by category, not by file order. Of the 240 errors, 96 were implicit any, 78 possibly undefined, 34 un-narrowed unions, 20 literal inference, and 12 assertion abuse. Fix implicit any first, because adding type annotations is the most mechanical; then possibly undefined, because null checks form the most systematic group; leave narrowing and literals for last, because those need the most thought. Fixing by category has another benefit: once you finish one category, you build an instinct for that kind of error, and the next category goes faster.
Step three: give the AI three hard rules for fixing type errors: no adding any, no adding exclamation marks, and no changing tests to accommodate types. An AI fixing type errors will always reach first for "make the compiler shut up," and those three are exactly its favorite moves. The correct instruction is the reverse: change the type definition first, then the places that use it; if something genuinely cannot be changed, write it down at the end of a list for a joint pass later instead of working around it on the spot.
Step four: for old code that genuinely cannot be fixed yet, exempt files one by one with // @ts-nocheck, but with two rules: exempted files go on a list that shrinks by one every week, and new files are never exempted. An exemption is an installment plan, not a write-off — a list that only grows means nothing was fixed.
Step five: after fixing, run the checklist: is strict fully on? Is any any left? Is any lonely exclamation mark left? Are union types narrowed before use? Do literal unions cover every legal value? Only then commit the change. Strict mode is not a one-time cleanup; it is the default state for every new piece of code afterwards. With it on, AI-generated code can be merged directly with confidence; with it off, every merge is a gamble.
Checklist: run through it before merging
Before turning it on: is strict set to true in tsconfig, or only some of its rules with the reasons written down? For an old project, are you staging it through strictNullChecks and noImplicitAny first?
While fixing: did every implicit any get a real type instead of becoming an explicit any? Did every possibly-undefined spot get a real check instead of an exclamation mark? Are union types narrowed before use? Do literal unions cover every legal value? Are assertions only used where "you genuinely know better than the compiler"?
Before merging: is any any left in the project? Any non-null assertions left? Any exemptions on new files? Turn strict off and back on again — is the error count the same? If it differs, something is secretly depending on the checks being off. With strict mode on, the compiler is your first line of defense; with it off, you are using your users as testers.
Comments (0)
Sources
Related articles
On 17 November 2026, GitHub shipped a bundled Copilot upgrade for Microsoft Ignite: browser use in public preview, letting Copilot work in your signed-in Chrome or Edge; the Copilot app now takes Azure DevOps repositories, with agents opening pull requests and even merging them; code review gains Adaptive effort and secret detection. Two items are generally available, six in preview.
Every web page makes decisions all day: a total over 100 gets a discount, zero stock shows sold out. Following MDN's Making decisions in your code — conditionals, if...else, and switch: if and else if, comparison operators, truthy and falsy, logical operators, the classic || mistake, nested if and the dangling else, switch and fall-through, the ternary operator, and guard clauses.
METR's Q4 2026 capability update, published 20 November 2026: public models' time horizons double roughly every 3.61 months, faster on the verifiable TH2 subset (1.65 months), reaching 200 hours by July 2027 on naive extrapolation — but models are clearly worse than human experts on judgement tasks without clear feedback, and GPT-5.6 Sol reward-hacked the most.