Skip to content

Unsafe as type casts can crash the app at runtime #92882

Closed

Description

@blimpich

Problem

Coming from this discussion, App lets developers use as type casts that override TypeScript's type checking, so a value can be treated as a type it isn't. When the real value doesn't match (most commonly it's actually undefined), the code compiles and ships fine but crashes at runtime. A concrete example is Sentry APP-714 — a Cannot read properties of undefined crash caused by an object that was cast to a non-nullable type when it could actually be undefined.

Reproduction Steps

These describe the class of bug (production); the representative incident is APP-714.

  1. Write code that casts a value whose real type is wider/nullable, e.g. const data = response as Foo; where response is actually Foo | undefined.
  2. Access a property or method on it: data.bar();
  3. Ship it — tsc and lint both pass.
  4. At runtime, hit the path where the value is undefined.
  • Expected Behavior: A type-safety check flags the unsafe cast at build time, so the crash is prevented before it ships.
  • Actual Behavior: The cast silently bypasses type checking, the build is clean, and the app crashes at runtime with Cannot read properties of undefined.

Solution

Enable the @typescript-eslint/no-unsafe-type-assertion ESLint rule as an error, with existing violations grandfathered via eslint-seatbelt so it blocks new unsafe casts without requiring a big upfront cleanup. This is implemented in PR #92833.

Extra context
  • The rule catches assertions that narrow to a less-safe type, including the as unknown as X loophole, which tsc alone does not catch.
  • Baseline at time of writing: 6,587 existing violations across 1,358 files, grandfathered so the rule errors only on new violations and ratchets down over time.
  • Originated from Slack discussions:
  • Note: this is ESLint (typescript-eslint) type-aware linting, which is memory-heavy and separate from the tsc typecheck job; the TypeScript 7 / tsgo speedup does not apply to it.

– written by Claude on Ben's behalf

Activity

  1. self-assigned this
    on Jun 8, 2026
  2. changed the title [-]Unsafe `as` type casts can crash the app at runtime[/-] [+][Due for payment 2026-06-17] Unsafe `as` type casts can crash the app at runtime[/+] on Jun 10, 2026
  3. melvin-bot commented on Jun 10, 2026

    @melvin-bot

    Reviewing label has been removed, please complete the "BugZero Checklist".

  4. melvin-bot commented on Jun 10, 2026

    @melvin-bot

    The solution for this issue has been 🚀 deployed to production 🚀 in version 9.4.1-6 and is now subject to a 7-day regression period 📆. Here is the list of pull requests that resolve this issue:

    If no regressions arise, payment will be issued on 2026-06-17. 🎊

  5. changed the title [-][Due for payment 2026-06-17] Unsafe `as` type casts can crash the app at runtime[/-] [+]Unsafe `as` type casts can crash the app at runtime[/+] on Jun 25, 2026
  6. blimpich commented on Jun 25, 2026

    @blimpich
    ContributorAuthor

    Playbook for reducing @typescript-eslint/no-unsafe-type-assertion (notes for future agents)

    This is a brain-dump from two completed batches so the next person/agent starts on the right foot rather than re-discovering everything. Prior work: #92833 (enabled the rule + seatbelt baseline), #92979 (the createMock helper + first 8 test files), #94623 (7 more test files, −518 violations).

    The big picture

    • ~6,000 violations are grandfathered in config/eslint/eslint.seatbelt.tsv. Roughly two-thirds live in test files that build mock fixtures with {...} as unknown as SomeType.
    • Those casts exist because the mock data is wrong (numeric IDs where the type wants strings, misspelled/renamed fields, fields that don't exist). The cast was silencing the type checker and hiding genuine bugs. So this is not a cosmetic refactor — fixing it surfaces real mistakes you then have to correct.
    • A mechanical codemod alone does not work. In a 30-file trial, only ~3% auto-converted cleanly; the rest needed type errors fixed by hand.

    The approach that works

    A tiny typed helper, already on main at tests/utils/createMock.ts:

    function createMock<T>(value: PartialDeep<T, {recurseIntoArrays: true}>): T {
        return value as T;
    }

    Replace {...} as unknown as T with createMock<T>({...}). The single unavoidable as T is isolated inside the helper (baselined once); every call site is now type-checked.

    What it catches (verified empirically): wrong/misspelled field names (excess-property error), wrong value types, and the same recursively through nested objects and array elements (that's why {recurseIntoArrays: true} is mandatory — type-fest PartialDeep does NOT recurse arrays by default, and without it every createMock<X[]>([{...}]) breaks).
    What it intentionally allows: omitting fields. That's the whole point of a mock — you only specify what the test needs. It does not force complete objects.

    Which files to target — and which to skip

    Not every top-violation file is a good fit. Check the actual reduction per file before committing, because the codemod wraps every object/array literal cast but only some are real violations:

    • ✅ Good fits: files whose violations are mock object/array literals (e.g. ReportPrimaryActionUtilsTest 181→35, CardUtilsTest 152→56, PolicyUtilsTest 111→13).
    • ❌ Skip — non-literal casts: TSCompilerUtilsTest (AST-node casts), addPushParamsRouterExtension.test (navigation-state casts). The codemod did 85 conversions on the latter for only −2 violations — pure churn. If conversions ≫ reduction, drop the file.
    • ❌ Skip — runtime-meaningful untyped fields: Search/list test mocks often carry fields the base type doesn't declare but production reads at runtime (e.g. a transaction mock with policyID, read by getSections). createMock forces you to delete them to satisfy the type; the file then passes typecheck but fails at runtime. SearchUIUtilsTest broke 2 tests this way and had to be dropped. These need a Search-specific type or should stay grandfathered.
    • ❌ Leave individual casts grandfathered for WorkspaceCardsList (Record<string,Card> & {cardList?} — an index-signature intersection) and Onyx.multiSet({[templateLiteralKey]: ...}) collection inputs. PartialDeep can't represent these; the original casts work around type-system limits, not bugs. Restore them to as unknown as T.

    Step-by-step

    1. Branch from main (createMock is already there). A .claude/worktrees/* worktree works, but symlink node_modules from the main checkout so tooling runs.
    2. Run a ts-morph codemod that converts only object/array-literal casts ({...} as T / {...} as unknown as T) to createMock<T>({...}), skips as const, and adds the import. Run node with NODE_PATH=<main>/node_modules if the script lives outside the repo.
    3. prettier --write + eslint --fix the converted files (fixes import order).
    4. Typecheck to surface the hidden bugs. Fix them at the root — rename misspelled fields, correct value types (numeric ID → string), remove genuinely-bogus fields. Never add as any, as unknown, @ts-expect-error, @ts-ignore, or eslint-disable, and never loosen the createMock<T> type argument. Parallelizing one agent per heavy file (Sonnet) works well.
    5. Regenerate the seatbelt baseline (see below) and run the test suites.
    6. Verify independently — never trust an agent's self-report. Re-run the gate yourself.

    Gotchas that cost real time

    Expand
    • Never convert a cast inside a jest.mock(...) factory. Factories are hoisted above imports, so createMock is out of scope → ReferenceError: module factory ... not allowed to reference out-of-scope variables. Leave those as the original.
    • Regenerating the baseline: seatbelt is configured readOnly: true locally (validates only, won't rewrite the tsv). To persist the reduced counts, run eslint with SEATBELT_READ_ONLY=0 SEATBELT_FROZEN=0. Type-aware linting of big test files needs a large heap — NODE_OPTIONS=--max_old_space_size=24576 (8 GB OOMs). Linting only the changed files updates just their rows and preserves the rest. This step is mandatory: CI runs frozen (CI=1), which turns decreases into errors, so a reduction without re-baselining fails CI with "Thank you for fixing N errors".
    • Local Jest can't run from a worktree (haste-map duplicate-mock confusion + the jest/setup.ts ReactNativeHybridApp mock not resolving under a symlinked node_modules). Use tsgo + the eslint-seatbelt frozen check to verify locally and rely on CI for the runtime test gate.
    • tsgo noise to ignore: .claude/worktrees/* paths (other worktrees) and TS2558 on the repo's require<typeof X>() augmentation — both are false positives that tsc/CI handle. Filter them out when reading tsgo output.
    • Production files are a different track. ~1/3 of violations are in src/. createMock is test-only; production casts need real type-narrowing (type guards / discriminated unions), which is riskier work — keep it separate from the test-file batches.

    PR conventions

    Test-only, so prefix the title with [NO QA]. In Fixed Issues use For https://github.com/Expensify/App/issues/92882 (non-closing — this is the umbrella, each batch is partial). Keep the description short and in plain English. Each batch is best shipped as a bounded PR (the binding constraint is reviewer bandwidth + merge churn, not generation cost), then let seatbelt's auto-ratchet handle the long tail.

    – written by Claude on Ben's behalf

  7. blimpich commented on Jun 26, 2026

    @blimpich
    ContributorAuthor

    I think this has served it's purpose as an issue I've used to understand this eslint error better. Going to close and open up a different issue to handle this more systematically

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions