[typescript-fetch] Fix TS2590 in instanceOf guards for wide sanitized-name models (#23980)

Merged
SE
5mo ago
+33-32

Fixes #23980

Problem

As of 7.23.0 the typescript-fetch generator emits instanceOf<Model> type guards that fail to compile with TS2590: "Expression produces a union type that is too complex to represent" when a model has many required properties whose sanitized TS name differs from the JSON baseName (e.g. any snake_case API).

The dual name/baseName membership check added in #23497 reads through the value parameter (typed object) on every clause:

if ((!('awsRegion' in value) && !('aws_region' in value)) || (value['awsRegion'] === undefined && value['aws_region'] === undefined)) return false;

Because the function is a type predicate (value is Model), each in/index-access against value narrows the parameter, and the candidate union grows on every clause. With ~15+ sanitized required fields the union crosses the compiler's internal limit and trips TS2590. Skinny models stay under the threshold, which is why it was not caught by existing samples.

Fix

Read the membership and index-access checks in the hasSanitizedName branch through value as Record<string, any> so TypeScript no longer narrows the predicate on each clause. This keeps the dual-key (name + baseName) behavior introduced by #23497 while restoring compilable guards. The non-sanitized branch (single-key) is unchanged — it never accumulated the cross-product union and already compiles for wide models.

Only modelGeneric.mustache changed; the regenerated samples are a mechanical consequence.

Verification

  • Reproduced the failure: a model with 18 required snake_case properties generated on master produces a guard that fails tsc --noEmit with TS2590.
  • After the fix, the same spec generates a guard that compiles cleanly (tsc --noEmit --strict, exit 0).
  • Regenerated all typescript-fetch samples (./bin/generate-samples.sh ./bin/configs/typescript-fetch-*.yaml) — 9 model files updated; the changed snakecase-discriminator build's models type-check cleanly under --strict.

Verification done: 1 (no in-flight PR — gh pr list/code-search), 2 (no claims on the issue), 3 (fix is in the .mustache template + generated .ts), 4 (grepped the dual-key pattern on master, confirmed present), end-to-end repro before/after with tsc.


Summary by cubic

Fixes TS2590 (“union type too complex”) in typescript-fetch when generating instanceOf<Model> guards for models with many required fields whose TS names differ from their JSON baseName. Guards now compile while preserving dual-key checks.

  • Bug Fixes
    • Cast value to Record<string, any> for dual name/baseName membership and discriminator checks to stop type predicate narrowing.
    • Retains behavior from #23497; single-key path unchanged.
    • Updated modelGeneric.mustache; regenerated affected samples; updated TypeScriptFetchClientCodegenTest assertions to expect the casts.