$cat~/ai-config-context.md

The AI Can't Hallucinate What TypeScript Won't Compile

12 min read

i spent way too long writing elaborate system prompts before realizing the obvious.

my tsconfig.json was sitting there with strict: false. the linter was whatever create-next-app spit out when i started that project. i was crafting paragraphs about code style, import conventions, variable naming. meanwhile the compiler wasn't checking anything.

config files are not suggestions. they're walls. the compiler doesn't give a shit how politely i asked Claude to avoid unused variables. TypeScript will just error. the linter will just fail. the build will just break.

that's not a bug. that's the entire point.

THE PROMPT ENGINEERING COPE

the "better prompts" crowd loves context. add more examples. be more specific. give the AI more information about what you want.

they're not wrong. context matters.

but they're solving the problem in the most fragile way possible.

every prompt is ephemeral. you write it, send it, it's gone. next session? starting from scratch. sure, you can save prompts, build elaborate injection systems. but that's work. every. single. session.

config files are permanent. checked into git. run automatically. they don't care if you forgot to paste your carefully crafted system prompt. they're there, doing their job, whether you remember them or not.

prompt engineering is manual quality control. strict configs are automated quality control.

anyone who's shipped software knows which one actually works.

WHAT I LEARNED THE HARD WAY

let me tell you what happened when i let AI write code without strict configs.

dead imports everywhere. i'd generate a file and find 15 imports where 12 were completely unused. useState, useEffect, useCallback, useMemo, useRef from React because maybe i'd need it. then i'd implement the component with just useState and leave the rest rotting.

hallucinated APIs. Claude's training data includes every version of every library ever. i asked it to use axios and got syntax from 2019. without type checking, it sailed right through. i didn't know until runtime when the app crashed.

truthy/falsy bugs that cost me hours. i wrote if (result) when result was a number. guess what happens when result is 0? it's valid data, but i treated it as false. classic.

magic numbers sprinkled everywhere. 0.08 for a tax rate. 86400000 for milliseconds in a day. no constants, no documentation. i couldn't maintain my own code six months later.

console.log in production. my debugging habits leaked straight to prod. "Fetching user:", "Response:", sometimes even logging sensitive data. security nightmare i caught by accident.

the solution wasn't better prompts. it was stricter configs.

ESLINT AS FIRST DEFENSE

my ESLint config isn't a style guide. it's a bouncer. every rule at error. no warnings. no exceptions.

Unused Code Detection

typescript
"unused-imports/no-unused-imports": "error", "unused-imports/no-unused-vars": [ "error", { vars: "all", args: "after-used", argsIgnorePattern: "^_" }, ],

these rules from eslint-plugin-unused-imports catch what TypeScript misses. and they're auto-fixable. when i generate a file with 7 unused imports, eslint --fix strips them out automatically. the AI doesn't need to "learn" anything. the tooling cleans up after it.

Strict Boolean Expressions

this is the rule that changed everything:

typescript
"@typescript-eslint/strict-boolean-expressions": ["error", { allowString: false, allowNumber: false, allowNullableObject: true, allowNullableBoolean: false, allowNullableString: false, allowNullableNumber: false, allowAny: false, }],

the allowNullableBoolean: false setting is brutal but necessary. here's why:

typescript
const isActive: boolean | undefined = getUserStatus(); if (isActive) { ... } // ERROR! not allowed

wait, why is checking a boolean in an if statement an error???

because undefined is falsy. so if (isActive) is false for both undefined AND false. the rule forces you to distinguish "not set" from "explicitly false":

typescript
if (isActive === true) { ... } // explicit check for true if (isActive === false) { ... } // explicit check for false if (isActive === undefined) { ... } // explicit check for not set

i hated this rule at first. felt like unnecessary verbosity. then i found a bug where i was treating "user hasn't set preference" the same as "user explicitly declined." different meanings, same falsy value. the rule would have caught it.

even better: it catches when i forget to await async functions:

typescript
if (isValid()) { ... } // ERROR: Promise<boolean> is not boolean

the Promise object is always truthy, even if it resolves to false. i've shipped this bug before. never again.

Documentation

Explicit Return Types

typescript
"@typescript-eslint/explicit-function-return-type": ["error", { allowExpressions: true, allowTypedFunctionExpressions: true, allowHigherOrderFunctions: true, allowDirectConstAssertionInArrowFunctions: true, }],

i used to have this off. "TypeScript infers correctly, why force verbosity?"

because i kept changing function contracts silently:

typescript
function getAge(person: Person) { return calculateAge(person.birthdate); } function getAge(person: Person) { if (person.birthdate === undefined) return null; // oops! return calculateAge(person.birthdate); }

first version: returns number. second version: returns number | null. breaking change. with explicit return types, this is a compile error. the contract is documented in code, not left to inference.

Documentation

No Console

typescript
"no-console": "error",

i sprinkle console.log everywhere for "debugging." then forget to remove them:

typescript
console.log("Card number:", card.number); // shipped to prod console.log("CVV:", card.cvv); // security incident

force structured logging. no exceptions.

Magic Numbers Banned

typescript
"no-magic-numbers": ["error", { ignore: [0, 1, -1], ignoreArrayIndexes: true, ignoreDefaultValues: true, enforceConst: true, }],

i used to say "magic numbers are fine, sometimes 0.08 is more readable than TAX_RATE."

i was wrong. i found 86400000 scattered through my codebase. 0.15 in three different files meaning three different things. named constants force documentation.

Unicorn Rules

typescript
"unicorn/no-null": "error", "unicorn/no-array-reduce": "error",

no null. pick one: null or undefined. i was using both inconsistently, creating type chaos. eslint-plugin-unicorn standardizes on undefined.

no reduce. i love clever reduce chains that are impossible to debug:

typescript
const productsByType = products.reduce( (accumulator, product) => ({ ...accumulator, [product.type]: [...(accumulator[product.type] || []), product], }), {} as Record<string, Product[]> ); const productsByType = Object.groupBy(products, (p) => p.type);

the rule forces the readable version.

React Hooks at Error Level

typescript
"react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "error",

i upgraded exhaustive-deps from warn to error. i constantly generate incomplete dependency arrays:

typescript
useEffect(() => { fetchData(userId); }, []);

missing userId means it never refetches when userId changes. this isn't a style preference. this is a functional bug. the component literally won't work correctly.

The Full Config

typescript
import js from "@eslint/js"; import globals from "globals"; import tseslint from "typescript-eslint"; import unusedImports from "eslint-plugin-unused-imports"; import unicorn from "eslint-plugin-unicorn"; import { fixupPluginRules } from "@eslint/compat"; import react from "eslint-plugin-react"; import reactHooks from "eslint-plugin-react-hooks"; export default tseslint.config( { plugins: { "@typescript-eslint": tseslint.plugin, "unused-imports": unusedImports, react: fixupPluginRules(react), "react-hooks": fixupPluginRules(reactHooks), }, settings: { react: { version: "detect" }, }, }, { ignores: [ "**/node_modules/", "**/dist/", "**/build/", "**/coverage/", "**/.next/", "**/.turbo/", "**/.vercel/", "*.min.js", "*.bundle.js", "**/*.config.js", "**/*.config.ts", "tests/", "**/*.test.ts", "**/*.test.js", "**/*.test.tsx", "**/*.test.jsx", "**/__tests__/**", ], }, { files: ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"] }, { languageOptions: { globals: { ...globals.browser, ...globals.node, ...globals.es2021, }, parserOptions: { project: ["./tsconfig.json"], tsconfigRootDir: import.meta.dirname, }, }, }, js.configs.recommended, ...tseslint.configs.recommendedTypeChecked, unicorn.configs["recommended"], { rules: { indent: ["error", 2], "linebreak-style": ["error", "unix"], semi: ["error", "always"], "no-console": "error", "no-magic-numbers": ["error", { ignore: [0, 1, -1], ignoreArrayIndexes: true, ignoreDefaultValues: true, enforceConst: true, }], "@typescript-eslint/no-magic-numbers": ["error", { ignore: [0, 1, -1], ignoreArrayIndexes: true, ignoreDefaultValues: true, ignoreEnums: true, ignoreNumericLiteralTypes: true, ignoreReadonlyClassProperties: true, ignoreTypeIndexes: true, }], "@typescript-eslint/explicit-function-return-type": ["error", { allowExpressions: true, allowTypedFunctionExpressions: true, allowHigherOrderFunctions: true, allowDirectConstAssertionInArrowFunctions: true, }], "@typescript-eslint/strict-boolean-expressions": ["error", { allowString: false, allowNumber: false, allowNullableObject: true, allowNullableBoolean: false, allowNullableString: false, allowNullableNumber: false, allowAny: false, }], "@typescript-eslint/only-throw-error": "error", "@typescript-eslint/no-unused-vars": "off", "unused-imports/no-unused-imports": "error", "unused-imports/no-unused-vars": [ "error", { vars: "all", args: "after-used", argsIgnorePattern: "^_" }, ], "unicorn/no-array-reduce": "error", "unicorn/prefer-at": "error", "unicorn/no-useless-undefined": "error", "unicorn/expiring-todo-comments": ["error", { allowWarningComments: false, }], "unicorn/import-style": "error", "unicorn/filename-case": ["error", { cases: { kebabCase: true, pascalCase: true, }, }], "unicorn/no-null": "error", "unicorn/prefer-module": "error", "react/react-in-jsx-scope": "off", "react/prop-types": "off", "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "error", "sort-imports": ["error", { ignoreCase: true, ignoreDeclarationSort: true, ignoreMemberSort: false, }], }, } );

TYPESCRIPT: EVERY STRICT FLAG ENABLED

here's the thing about strict: true. it's not enough.

strict: true enables a baseline. but there are additional flags that catch more mistakes. i enable all of them.

Core Strict Mode

json
"strict": true, "noImplicitAny": true, "strictNullChecks": true, "strictFunctionTypes": true, "strictBindCallApply": true, "strictPropertyInitialization": true, "noImplicitThis": true, "useUnknownInCatchVariables": true, "alwaysStrict": true,

according to Pierre-Marie Dartus's research, well-defined types act as "guardrails and guides, not just for human developers, but for our AI partners too." the types provide enough information that AI can generate valid code without needing to load your entire codebase into context.

Unchecked Indexed Access

json
"noUncheckedIndexedAccess": true,

this is the big one. i kept assuming array access always returns a value:

typescript
const users: User[] = []; const firstUser = users[0]; console.log(firstUser.name);

without the flag: firstUser type is User. lies. it's actually undefined because the array is empty. runtime crash.

with noUncheckedIndexedAccess: firstUser type is User | undefined. compile error when i try to access .name without checking. correct.

i love accessing array[i] without bounds checking. this flag forces explicit handling.

Documentation

Exact Optional Property Types

json
"exactOptionalPropertyTypes": true,

optional (?) should mean "might not exist," not "might be undefined." i often assign undefined explicitly to optional properties, corrupting data:

typescript
interface User { nickname?: string; } const user: User = { nickname: undefined };

with the flag: error. the property EXISTS but has undefined value. that's different from not existing at all. JSON.stringify handles them differently. spreading handles them differently.

Documentation

No Implicit Returns

json
"noImplicitReturns": true,

i generate functions with incomplete logic, forgetting to return in all branches:

typescript
function getDiscount(tier: "bronze" | "silver" | "gold"): number { if (tier === "bronze") return 5; else if (tier === "silver") return 10; }

forgot gold. implicitly returns undefined. error: not all code paths return a value.

No Property Access From Index Signature

json
"noPropertyAccessFromIndexSignature": true,

forces bracket notation for dynamic properties, making uncertainty explicit:

typescript
interface Settings { speed: "fast" | "slow"; [key: string]: string; } settings.speed; // OK settings.username; // ERROR, must use settings["username"]

dot notation implies "i know this exists." bracket notation signals "this is uncertain." the distinction matters.

The Full Config

json
{ "compilerOptions": { "target": "ES2022", "module": "ESNext", "lib": ["ES2023", "DOM", "DOM.Iterable"], "moduleResolution": "bundler", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "incremental": true, "skipLibCheck": true, "baseUrl": ".", "paths": { "@/*": ["./*"] }, "strict": true, "noImplicitAny": true, "strictNullChecks": true, "strictFunctionTypes": true, "strictBindCallApply": true, "strictPropertyInitialization": true, "noImplicitThis": true, "useUnknownInCatchVariables": true, "alwaysStrict": true, "noUnusedLocals": true, "noUnusedParameters": true, "exactOptionalPropertyTypes": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "noUncheckedIndexedAccess": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "allowUnusedLabels": false, "allowUnreachableCode": false, "forceConsistentCasingInFileNames": true, "verbatimModuleSyntax": false, "allowJs": true, "jsx": "preserve", "plugins": [ { "name": "next" } ] }, "include": [ "**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts", ".next/types/**/*.ts" ], "exclude": [ "**/.next", "**/node_modules", "**/dist", "**/build", "**/coverage", "**/tests/**/*", "**/test/**/*", "**/__tests__/**/*", "**/*.test.ts", "**/*.spec.ts" ] }

KNIP: PROJECT-LEVEL DEAD CODE DETECTION

ESLint and TypeScript operate at the file level. Knip operates at the project level.

the difference: "is this variable used in this file?" versus "is this export used anywhere in the entire codebase?"

my Knip config is aggressive. every rule at error. no warnings.

typescript
rules: { files: "error", exports: "error", types: "error", duplicates: "error", binaries: "error", dependencies: "error", devDependencies: "error", unlisted: "error", }

unused exports increase bundle sizes, clutter the codebase, and mislead developers into thinking code is used when it isn't. Knip catches this at the project level.

i generate a lot of "helper" functions that end up unused. i'll create a formatCurrency utility because the task mentioned prices, then solve the problem a different way. without Knip, that dead export lives in my codebase forever, consuming tokens every time i include the file in context.

Knip also catches unused dependencies. when i add packages via npm install but don't end up using them, Knip flags it. clean dependencies, clean context.

The Full Config

typescript
import type { KnipConfig } from "knip"; const config: KnipConfig = { entry: [ "**/*.ts", "!**/*.test.ts", "!**/*.d.ts", ], project: [ "**/*.ts", "**/*.d.ts", ], ignore: [ "docs/**", "coverage/**", "dist/**", "tests/**", "**/*.js", ], ignoreFiles: [ "**/*.md", "tsconfig*.json", "eslint.config.*", "**/*.config.ts", "**/*.template.*", "node_modules/**", ], ignoreDependencies: [ "tsx", "ts-node", "typescript", "esbuild", "jiti", "vitest", "@vitest/coverage-v8", "@vitest/ui", "eslint", "@eslint/compat", "@typescript-eslint/eslint-plugin", "@typescript-eslint/parser", "typescript-eslint", "eslint-import-resolver-typescript", "eslint-plugin-import", "eslint-plugin-perfectionist", "eslint-plugin-react", "eslint-plugin-react-hooks", "eslint-plugin-unicorn", "eslint-plugin-unused-imports", "eslint-plugin-vitest", "globals", "knip", "autoprefixer", ], ignoreExportsUsedInFile: true, rules: { files: "error", exports: "error", types: "error", duplicates: "error", binaries: "error", dependencies: "error", devDependencies: "error", unlisted: "error", }, typescript: { config: ["tsconfig.json"], }, }; export default config;

THE META-POINT

your config files aren't just rules for humans. they're context injection that runs before every prompt.

when Claude Code works in my project, it sees linter errors in real-time. it sees TypeScript errors before i do. those errors shape its behavior. it's not reading my prompt and making a choice. it's running into a wall and being forced to find another path.

according to research on type-constrained code generation, on average 94% of compilation errors in LLM-generated code result from failing type checks. ninety-four percent. that's not prompt engineering. that's the compiler doing its job.

strict configs = fewer hallucinations.

not because the AI "learned" from my configs. but because the tooling catches mistakes immediately, forcing the AI to generate different code.

a prompt is a suggestion. a config is a constraint. you can ignore a suggestion. you can't walk through a wall.

THE PATTERN

AI generates code -> strict config catches violation -> AI sees error -> AI fixes -> correct code

without strict configs:

AI generates code -> looks correct -> ships to production -> runtime error -> 3am debugging

i know what you're thinking. "that's a lot of config for a new project."

yes. it is.

but here's the math: you set this up once. then every AI-generated file, every refactor, every iteration. all filtered through these constraints automatically.

the alternative is manually catching every unused import, every dead variable, every truthy/falsy bug. or worse, not catching them at all and slowly drowning in accumulated cruft.

strict configs are compound interest for code quality. small upfront investment, exponential returns over time.


your prompt is what you ask the AI to do.

your config is what you force the AI to do.

one is a request. the other is a requirement.

set up the configs. let them do the work.

written by george (fullstacktard), co-founder and CTO of Signal8, market intelligence for retail traders: SEC filings, dilution tracking, insider and congress trades.