Hand-written TypeScript interfaces drift from Java models over time. The reliable approach is to generate them from one source of truth. Option 1 — OpenAPI generation (most common) - Generate an OpenAPI specification from Spring Boot with springdoc-openapi (/v3/api-docs). - Make the spec accurate: annotate response types and error responses, mark required fields (@Schema(requiredMode = REQUIRED) or Bean Validation annotations such as @NotNull, which springdoc reflects), document enums and nullable fields. - Generate TypeScript in the frontend build: - openapi-typescript for types only, - orval or openapi-generator (typescript-fetch or typescript-axios) for typed clients, including TanStack Query hooks with orval. - Automate it: the backend build exports the spec (springdoc's Maven or Gradle plugin), publishes it as an artifact, and the frontend regenerates on change. CI fails if committed generated code is out of date. Option 2 — Contract-first - Write the OpenAPI document first, review API changes in pull requests, and generate both Spring interfaces (openapi-generator's spring generator) and TypeScript clients from it. Both sides must implement the same contract. Option 3 — Direct type generation - Tools such as typescript-generator (cz.habarta) convert Java classes into TypeScript definitions; simpler but less descriptive of endpoints. Detecting breaking changes - Diff specs in pull requests (oasdiff, openapi-diff) to catch removed or renamed fields. - Contract tests (Pact or Spring Cloud Contract) verify that real responses match what the frontend expects. - TypeScript compilation itself catches mismatches after regeneration. Runtime safety - TypeScript types disappear at runtime; validate critical responses with zod (orval can generate zod schemas) if needed. - Be consistent about JSON conventions: Jackson naming strategy, date formats (ISO 8601 strings via JavaTimeModule), BigDecimal as string or number (decide explicitly to avoid precision loss), and enum serialisation. Evolution practices - Additive changes, optional new fields, deprecation before removal, and API versioning for breaking changes.
Ravindra Wadile · · 0 likes