Home / Articles

Practical notes: Keeping Frontend and Backend Types in Sync with Typescript

Operable walkthrough of Practical notes: Keeping Frontend and Backend Types in Sync with Typescript: contracts, checks, and drop-in code slots for teams shipping this pattern.

Publisher: REACTAPP.TOP7 min read1637 words

This article is published in English.

Sources: Keeping Frontend and Backend Types in Sync with Typescript Magic

Use this as an operator-facing rebuild of the ideas in “Keeping Frontend and Backend Types in Sync with Typescript Magic”: clear stages, ordered code slots, and recovery notes that survive a handoff.

The bug that has no stack trace

The The bug that has stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Keep render work cheap and push expensive derivation behind memoization only after measuring. Premature memo can hide stale props bugs.

// backend/src/topics/topics.service.ts
async findAll(): Promise<TopicRow[]> {
  return this.prisma.topic.findMany({ select: TOPIC_SELECT });
}
// frontend/src/types.ts
export interface TopicRow {
  id: string;
  code: string;
  requiresKey: boolean;
  // ...
}

Why this got urgent

The Why this got urgent stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Keep render work cheap and push expensive derivation behind memoization only after measuring. Premature memo can hide stale props bugs.

The idea

The The idea stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Keep render work cheap and push expensive derivation behind memoization only after measuring. Premature memo can hide stale props bugs.

// backend/contract/assert.ts

/** The wire shape of a server value: JSON.stringify turns Date into string. */
export type Jsonify<T> = T extends Date
  ? string
  : T extends (infer U)[]
    ? Jsonify<U>[]
    : T extends object
      ? { [K in keyof T]: Jsonify<T[K]> }
      : T;
/** Invariant (not merely assignable) equality - catches widened optionals. */
export type Equal<A, B> =
  (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2)
    ? true
    : false;
export type Expect<T extends true> = T;
/** The element type of a service method that resolves to an array. */
export type RowOf<T> = Jsonify<Awaited<T>> extends (infer U)[] ? U : never;
/** The resolved wire shape of a service method. */
export type ResultOf<T> = Jsonify<Awaited<T>>;
/** The row type of a paginated `{ rows, total }` service method. */
export type PagedRowOf<T> =
  Jsonify<Awaited<T>> extends { rows: (infer U)[] } ? U : never;
// backend/contract/api-contract.ts
import type { Equal, Expect, PagedRowOf, RowOf } from './assert';
import type { TopicsService } from '../src/topics/topics.service';
import type { ContactRequestsService } from '../src/contact-requests/contact-requests.service';
import type { TopicRow, ContactRequestRow } from '../../frontend/src/types';

// GET /topics
export type _Topics = Expect<
  Equal<RowOf<ReturnType<TopicsService['findAll']>>, TopicRow>
>;
// GET /contact-requests (paginated)
export type _ContactRequests = Expect<
  Equal<PagedRowOf<ReturnType<ContactRequestsService['findAll']>>, ContactRequestRow>
>;

The typing magic, explained

The The typing magic explained stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Keep render work cheap and push expensive derivation behind memoization only after measuring. Premature memo can hide stale props bugs.

export type _Topics = Expect<
  Equal<RowOf<ReturnType<TopicsService['findAll']>>, TopicRow>
>;
type Equal<A, B> = A extends B ? (B extends A ? true : false) : false; // too loose
(<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2
export type RowOf<T> = Jsonify<Awaited<T>> extends (infer U)[] ? U : never;

Wire it to the method, not the query

The Wire it to the stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion. Keep render work cheap and push expensive derivation behind memoization only after measuring. Premature memo can hide stale props bugs. The Wire it to the stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

// Wrong: misses everything the method does after the query
Equal<Jsonify<TopicSelectResult>, TopicRow>
// Right: whatever the method actually resolves to
Equal<RowOf<ReturnType<TopicsService['findAll']>>, TopicRow>

Making it run

For the Making it run stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Colocate state with the component that owns the mutation. Lifting everything to a global store makes timing bugs harder to see.

// backend/tsconfig.contract.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "noEmit": true,
    "rootDir": "..",              // program spans both packages
    "module": "preserve",
    "moduleResolution": "bundler" // resolve the way the frontend's bundler does
  },
  "include": ["src/**/*", "contract/**/*", "../frontend/src/types.ts"]
}
{ "scripts": { "check:contract": "tsc -p tsconfig.contract.json" } }

Reading a failure

For the Reading a failure stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Colocate state with the component that owns the mutation. Lifting everything to a global store makes timing bugs harder to see.

type P1 = A extends B ? true : false;        // false => server is narrower / has extra
type P2 = B extends A ? true : false;        // false => frontend is wider
type Extra = Exclude<keyof A, keyof B>;      // fields the server sends, frontend lacks
type Missing = Exclude<keyof B, keyof A>;    // fields the frontend invented

What it costs, and where it doesn’t reach

For the What it costs and stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion. Colocate state with the component that owns the mutation. Lifting everything to a global store makes timing bugs harder to see. For the What it costs and stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

The point

When working through the The point stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Treat effects as synchronization with the outside world, not as a substitute for derived values during render.

Operational checklist

When working through the Operational checklist stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest.

Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.

Treat effects as synchronization with the outside world, not as a substitute for derived values during render.

Pin dependency versions and record the image digest that ran the demo. Reproducibility beats tribal knowledge.

Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

Treat effects as synchronization with the outside world, not as a substitute for derived values during render.

Before promoting the stack, freeze versions, capture a golden transcript for the critical path, and confirm rollback steps. Shared environments need rate limits, tenancy checks, and a clear owner for secret rotation. Prefer boring reliability over clever one-off demos.

Batch note for 99a16b87e27d: keep provider keys out of the repo, set a per-session token ceiling, and store transcripts next to the eval fixtures so later model swaps stay comparable.