Repository navigation
Description
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.
- Write code that casts a value whose real type is wider/nullable, e.g.
const data = response as Foo;whereresponseis actuallyFoo | undefined. - Access a property or method on it:
data.bar(); - Ship it —
tscand lint both pass. - 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 Xloophole, whichtscalone 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:
- Proposal to discourage unsafe
ascasts: https://expensify.slack.com/archives/C08CZDJFJ77/p1772767032324279 - Related lint/typecheck memory pressure (tsc OOM / tsgo): https://expensify.slack.com/archives/C01GTK53T8Q/p1780683196120609
- Proposal to discourage unsafe
- Note: this is ESLint (typescript-eslint) type-aware linting, which is memory-heavy and separate from the
tsctypecheck job; the TypeScript 7 / tsgo speedup does not apply to it.
– written by Claude on Ben's behalf
Activity
[-]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[/+]melvin-bot commentedon Jun 10, 2026
Reviewinglabel has been removed, please complete the "BugZero Checklist".melvin-bot commentedon Jun 10, 2026
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. 🎊
[-][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[/+]blimpich commentedon Jun 25, 2026
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
createMockhelper + first 8 test files), #94623 (7 more test files, −518 violations).The big picture
config/eslint/eslint.seatbelt.tsv. Roughly two-thirds live in test files that build mock fixtures with{...} as unknown as SomeType.The approach that works
A tiny typed helper, already on
mainattests/utils/createMock.ts:Replace
{...} as unknown as TwithcreateMock<T>({...}). The single unavoidableas Tis 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-festPartialDeepdoes NOT recurse arrays by default, and without it everycreateMock<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:
ReportPrimaryActionUtilsTest181→35,CardUtilsTest152→56,PolicyUtilsTest111→13).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.policyID, read bygetSections).createMockforces you to delete them to satisfy the type; the file then passes typecheck but fails at runtime.SearchUIUtilsTestbroke 2 tests this way and had to be dropped. These need a Search-specific type or should stay grandfathered.WorkspaceCardsList(Record<string,Card> & {cardList?}— an index-signature intersection) andOnyx.multiSet({[templateLiteralKey]: ...})collection inputs.PartialDeepcan't represent these; the original casts work around type-system limits, not bugs. Restore them toas unknown as T.Step-by-step
main(createMock is already there). A.claude/worktrees/*worktree works, but symlinknode_modulesfrom the main checkout so tooling runs.{...} as T/{...} as unknown as T) tocreateMock<T>({...}), skipsas const, and adds the import. Run node withNODE_PATH=<main>/node_modulesif the script lives outside the repo.prettier --write+eslint --fixthe converted files (fixes import order).as any,as unknown,@ts-expect-error,@ts-ignore, oreslint-disable, and never loosen thecreateMock<T>type argument. Parallelizing one agent per heavy file (Sonnet) works well.Gotchas that cost real time
Expand
jest.mock(...)factory. Factories are hoisted above imports, socreateMockis out of scope →ReferenceError: module factory ... not allowed to reference out-of-scope variables. Leave those as the original.readOnly: truelocally (validates only, won't rewrite the tsv). To persist the reduced counts, run eslint withSEATBELT_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".jest/setup.tsReactNativeHybridAppmock not resolving under a symlinkednode_modules). Usetsgo+ the eslint-seatbelt frozen check to verify locally and rely on CI for the runtime test gate..claude/worktrees/*paths (other worktrees) andTS2558on the repo'srequire<typeof X>()augmentation — both are false positives thattsc/CI handle. Filter them out when reading tsgo output.src/.createMockis 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 useFor 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
blimpich commentedon Jun 26, 2026
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