TypeScript Anti-Slop — Senior Engineering Standard
Goal and scope
This skill is an engineering-quality reviewer and coding guardrail, not an AI-authorship detector. Applicable to: TypeScript applications, React/Next.js frontends, Node TypeScript services, libraries, clients and monorepos. Find actionable defects and unnecessary complexity; do not make style/LOC a proxy for engineering competence.
Modes and authorization
- AUDIT (default): Read-only. Inspect and report with
path:line, evidence, severity and confidence. Never edit or delete. - IMPLEMENT: User asks to write/extend code. Search for the existing owning implementation first; modify that file rather than creating another implementation. New files require a real new responsibility.
- REFACTOR: User explicitly requests changes/cleanup/fixes. Make behavior-preserving changes within scope and delete verified superseded files after consumers move. Do not silently rewrite public behavior.
- If user requests audit + fixes, audit first, then correct the authorized scope. Respect uncommitted changes and non-code assets. Do not remove applied migrations, user data, generated output without identified source, or files whose ownership is uncertain.
Mandatory file replacement protocol
For every IMPLEMENT or REFACTOR task read and obey references/replacement-protocol.md. It defines the inventory, replacement ledger, migration of imports/routes/registrations, safe deletion, proof, and failure gates. This requirement takes precedence over the convenience of adding new modules.
Hard invariant: one active authoritative implementation per responsibility, unless a documented compatibility/versioning requirement justifies coexistence. No *_v2, *_new, *_fixed, duplicate handlers, duplicate service files, or parallel worker implementations as a default solution. In REFACTOR, once the old implementation is truly obsolete and all callers migrated, remove the old code file—not just deprecate it in a comment. If ownership or external consumers are unknown, do not delete: explain the blocker.
Core workflow
- Read repository instructions, manifests, build and test config. Discover entry points, imports and symbols. Inspect
git status --shortand recent diffs when relevant. - Define domain invariants, error/cancellation semantics, data formats, public contracts and concurrency ownership before calling anything slop.
- Map a coherent code domain (typically 10–15 related files, but trace cross-file execution paths regardless of count).
- Run applicable deterministic checks (below), recording actual results and missing tools. Never claim a check ran when it did not.
- Examine the rules below. For each candidate distinguish symptom, demonstrated harm, legitimate reason, minimal remedy, regression proof.
- In AUDIT, issue a prioritized report; in IMPLEMENT/REFACTOR, use the replacement ledger and change only the authorized responsibility.
- After code changes migrate every consumer, retire obsolete files, and run build/tests with runtime/error and concurrency paths where relevant. Search for the old symbols and inspect the final diff.
Automated diagnostics — adapt to repo conventions
npm run typecheck --if-present
npm run lint --if-present
npm test --if-present
npm run build --if-present
# If TypeScript is installed locally and project config matches:
npx tsc --noEmit
Use the repo's package manager/scripts; don't install packages speculatively. For typed linting, check the actual typescript-eslint config before claiming promise/unsafe-type rules ran. strict, noUncheckedIndexedAccess and exactOptionalPropertyTypes affect migration cost; propose staged adoption, not a blanket breaking config change.
36 slop-detection rules (TS01–TS36)
Treat every match as a hypothesis until you inspect context. The answer to “why is it needed?” matters more than appearances.
- TS01 any propagation: Signal: any enters core logic and hides unsafe property access. Legitimate exception: Narrow interop boundary with explicit validation. Remedy/verification: Prefer unknown and decode/narrow at boundary.
- TS02 Double-cast evasion: Signal: value as unknown as Foo asserts unsupported contract. Legitimate exception: Verified external schema or tested migration shim. Remedy/verification: Validate and transform rather than silence checker.
- TS03 Non-null assertion saturation: Signal: ! used on data that may genuinely be absent. Legitimate exception: Invariant formally established. Remedy/verification: Model missing state, guard and test.
- TS04 Suppression blanket: Signal: @ts-ignore / @ts-nocheck used broadly without justification. Legitimate exception: Narrow third-party type compatibility issue. Remedy/verification: Fix root type issue; scoped @ts-expect-error with comment when needed.
- TS05 Optional-everywhere interfaces: Signal: Core domain objects mark required fields optional and force fallback chains. Legitimate exception: Partial update/input DTO intentionally partial. Remedy/verification: Separate partial input, persisted model and output contracts.
- TS06 String-index signature everywhere: Signal: Record<string, any/unknown> replaces known object schema. Legitimate exception: Actually open keyset. Remedy/verification: Model explicit fields with validation at boundaries.
- TS07 Impossible state combinations: Signal: loading, success, error booleans can all be true. Legitimate exception: Orthogonal flags with proven invariants. Remedy/verification: Use discriminated union for mutually exclusive states.
- TS08 Unsafe exhaustive handling: Signal: switch/if silently ignores newly added union variant. Legitimate exception: Fallback deliberately part of contract. Remedy/verification: Use exhaustive never checks and tests.
- TS09 Promise intentionally ignored: Signal: void asyncCall() or missing await discards rejection/ordering. Legitimate exception: Explicit fire-and-forget supervised by owner. Remedy/verification: Await or use owned task with error policy.
- TS10 Async callback mismatch: Signal: async passed where void expected without error handling. Legitimate exception: Framework awaits/reports promise explicitly. Remedy/verification: Wrap with owned rejection handling, validate framework.
- TS11 Runtime trust in types: Signal: JSON.parse, request.body or fetch response cast to interface without validation. Legitimate exception: Trusted transport controlled and validated earlier. Remedy/verification: Validate runtime payload at trust boundary.
- TS12 Duplicate frontend/backend types: Signal: Two User/Job/DTO definitions diverge across packages. Legitimate exception: Versioned APIs with explicit transforms. Remedy/verification: Share generated schema or explicit contract tests.
- TS13 Type-schema drift: Signal: Zod/JSON schema/DB definitions differ from TS type definition. Legitimate exception: Intentional versioned model. Remedy/verification: Generate or test alignment; single source of truth.
- TS14 Generic-overengineering: Signal: Generic helpers require many type args for a single concrete use case. Legitimate exception: True reusable library constraint. Remedy/verification: Use concrete function/signature.
- TS15 Conditional-type labyrinth: Signal: Recursive conditional/mapped types obscure business rules. Legitimate exception: Library API genuinely needs expressive types. Remedy/verification: Flatten or hide behind small documented alias.
- TS16 Types in place of actual validation: Signal: Enum/union used to justify unchecked external input. Legitimate exception: Value is proven internal. Remedy/verification: Validate strings and numbers, fail clearly.
- TS17 Duplicate enum / literal definitions: Signal: Repeated status lists across services and UI. Legitimate exception: Independent protocol versions. Remedy/verification: Unify authoritative domain state and mappings.
- TS18 Barrel export cycles: Signal: index.ts re-export webs hide dependencies or create runtime cycles. Legitimate exception: Public API boundary supports stable contracts. Remedy/verification: Use direct imports where clearer and break cycles.
- TS19 Path alias disagreement: Signal: tsconfig path works in editor but not runtime/test/build. Legitimate exception: Bundler resolver configured consistently. Remedy/verification: Align toolchain and test deployed import resolution.
- TS20 Config multiplication: Signal: Multiple tsconfig/eslint configs disable checks unpredictably. Legitimate exception: Package-specific options documented. Remedy/verification: Deduplicate through explicit base and verify each project.
- TS21 Strictness erosion: Signal: strict disabled to quiet unrelated types; weak boundaries propagate. Legitimate exception: Incremental migration with tracked scope. Remedy/verification: Enable/restore appropriate checks and isolate legacy.
- TS22 Unchecked property indexing: Signal: Map/array access assumed present without bounds/presence check. Legitimate exception: Closed key space/invariant proven. Remedy/verification: Guard access; consider noUncheckedIndexedAccess.
- TS23 Optional/undefined confusion: Signal: {x: undefined} treated as identical to absent property at runtime. Legitimate exception: API defines them as same. Remedy/verification: Model optional semantics; consider exactOptionalPropertyTypes.
- TS24 Unsafe external JS interop: Signal: Unverified JS packages given custom declaration that asserts wishful types. Legitimate exception: Runtime API tested and version pinned. Remedy/verification: Validate interop and narrow declarations.
- TS25 Weak error types: Signal: catch(error) blindly asserts Error or absorbs unknown cause. Legitimate exception: Thrown values controlled by boundary. Remedy/verification: Narrow unknown and preserve error semantics.
- TS26 Duplicated API-client wrappers: Signal: New fetch wrapper introduced beside existing, with different auth/retry rules. Legitimate exception: Different trust/protocol boundary. Remedy/verification: Consolidate clients and update all callers.
- TS27 Duplicated schema validators: Signal: Repeated parse/validation logic drifts between endpoints/UI. Legitimate exception: Distinct boundary requirements. Remedy/verification: Share canonical input contract or test equivalence.
- TS28 False discriminants: Signal: Discriminated union compiles but runtime values are constructed inconsistently. Legitimate exception: Constructor guarantees invariant. Remedy/verification: Centralize constructors/decoder and test states.
- TS29 Type-only runtime confusion: Signal: Type import expected to provide runtime value/guard. Legitimate exception: Build tool intentionally transforms correctly. Remedy/verification: Use real runtime validator and runtime import.
- TS30 One giant types.ts: Signal: Unrelated domains share a monolithic type file. Legitimate exception: Public SDK surface truly unified. Remedy/verification: Group by owned domain, avoid over-fragmentation.
- TS31 Generated type edits: Signal: Hand-edit generated .d.ts/client output instead of schema/source. Legitimate exception: Generated artifact intentionally checked in but source absent. Remedy/verification: Change generator/source, regenerate and validate.
- TS32 Stale compatibility aliases: Signal: Old and new interfaces/exports both accepted after migration. Legitimate exception: Public API compatibility explicitly needed. Remedy/verification: Migrate callers and retire unused aliases/files.
- TS33 Unchecked async race: Signal: Concurrent UI or service requests overwrite newer state with stale result. Legitimate exception: Last-completion-wins is intended. Remedy/verification: Use request ownership/abort/versioning and test races.
- TS34 Excessive React effect logic: Signal: useEffect used to orchestrate domain state and duplicate data fetching. Legitimate exception: Genuine external synchronization. Remedy/verification: Derive state or use existing data layer; verify effects.
- TS35 Optional chaining as band-aid: Signal: a?.b?.c ?? default conceals broken internal invariants. Legitimate exception: Untrusted or optional input boundary. Remedy/verification: Fix contract, keep nullable checks only when legitimate.
- TS36 Unverified compilation target: Signal: TS typecheck passes but emitted JS runtime/package resolution fails. Legitimate exception: Existing E2E build proves target. Remedy/verification: Run build/tests against actual runtime and deployment.
Cross-file change and removal checklist
- Runtime validation for network/storage/IPC data: TypeScript types disappear at runtime.
tsconfigreferences, path aliases, barrel files, package exports, build-target module resolution and generated declarations.- Frontend async ownership (effects, request races, unmount/disconnect), client/server API schemas and monorepo contracts.
- Existing JavaScript consumers of exported types and entry points.
Also check source-level duplicates and runtime duplicates (two routes/workers registered for the same responsibility). A file may be statically referenced nowhere but loaded dynamically: before deletion verify startup paths, tests, deployment manifests, feature flags, and plugin/config entrypoints. If safe replacement cannot be proved, keep the file and clearly mark it BLOCKED FOR REMOVAL. Do not call the repository duplicate-free.
Severity / evidence standard
- CRITICAL: Credible data-loss/security/cross-tenant violation or irreversible corruption.
- HIGH: Silent failure, broken async/concurrency, duplicate side effect, production outage or unbounded resource use.
- MEDIUM: Demonstrable maintainability, correctness edge-case, resource or testing weakness.
- LOW: Local clarity/duplication improvement with limited impact.
- Confidence:
Confirmed(proved/reproduced) /Supported(strong cross-file evidence) /Heuristic(symptom only). Severity and confidence are separate.
Do not fabricate file paths, successful builds, metrics, causation, or evidence of human/AI authorship. For high-risk findings, trace a caller and a downstream effect, and give a concrete failure case.
Required output format
Scope: paths/modules reviewed; public/async/DB boundaries; tests/lints actually run
Findings:
- [RULE] path:line — severity | confidence
Symptom -> violated invariant -> demonstrated consequence
When acceptable -> smallest verified remedy -> test
Replacement ledger (if code was modified):
- responsibility | old file | edit-in-place / move / retire | new file
- modified: ...
- deleted: ... (proof of migrated references)
- retained: ... (external contract, unverified dynamic use, or user changes)
Validation: commands + pass/fail/not-run; old-symbol search; git diff check
Residual risks: unknown external consumers, migrations, unrun tests
Exit gates
- All applicable 36 rules considered, without manufacturing findings.
- No AUDIT-mode edits.
- When writing code: old owner searched first, no shadow implementation created.
- For replacement: every known consumer migrated; superseded code file removed when safe; exceptions explicitly justified.
-
git diff --name-statusand old-symbol/route search inspected. - Relevant compile/type/lint/build/tests (including failure behavior) run or accurately marked unavailable.
- Existing user changes, applied migrations, security and recovery safeguards preserved.