json-schema-to-typescript icon indicating copy to clipboard operation
json-schema-to-typescript copied to clipboard

fix(optimizer): simplify redundant intersections in allOf schemas

Open privatenumber opened this issue 2 months ago • 0 comments

Problem

When a JSON Schema uses allOf with $ref that overlap, the generated TypeScript contains redundant intersections and duplicate properties.

Example from the tsconfig.json schema:

export type CompilerOptions = {
  types?: (string | null)[] | null;
  target?: string | null;
  [k: string]: unknown;
} & ({
  types?: (string | null)[] | null;  // Duplicate
  target?: string | null;             // Duplicate
  [k: string]: unknown;
} | null);

This happens when:

  1. A schema definition is $ref’d multiple times
  2. One $ref wraps the base in an allOf with extra constraints
  3. The parser generates multiple AST nodes with the same name but different shapes

Before

export type CompilerOptions = {...} & ({...} | null);

Changes

  1. Optimizer (optimizer.ts)

    • Simplifies A & (A | null)A | null
    • Handles both (A & (A | null)) and (A | null) & A
    • Deduplicates intersections like A & B & A & B → A & B
  2. Generator (generator.ts)

    • Tracks generated type names with a Set
    • Skips duplicate export type declarations

After

export type CompilerOptions = {...} | null;

privatenumber avatar Oct 08 '25 07:10 privatenumber