DEV Community

Dan Kestrel
Dan Kestrel

Posted on

Catching TypeScript .d.ts Contract Drift Against Live APIs in CI

Unit tests with mocked JSON responses pass right up until the day your TypeScript SDK ships a .d.ts file that disagrees with production.

We recently audited an SDK upgrade and ran tsc --noEmit alongside a live integration suite against the real API. The compiler was completely happy, yet runtime checks immediately caught three contract bugs that unit mocks missed:

  1. A wrapped payload ({ ok: true, summary: { ... } }) typed as a flat object.
  2. Renamed boolean and counter fields (inCooldown and velocity in JSON vs cooldownActive and remainingSeconds in .d.ts).
  3. Nullable timestamps returning null at runtime while .d.ts declared ?: string without | null.

Why Unit Mocks Hide Contract Drift

When your test suite mocks fetch, you are testing your own assumptions rather than the server response. Under strictNullChecks, a missing | null union lets callers write new Date(contact.lastEmailedAt) or .startsWith(...) without any compiler warning.

Similarly, if a backend wraps a response in { ok, summary }, reading res.data.domain returns undefined at runtime even though TypeScript thinks it is a string.

Adding a Runtime Shape Guard in CI

Instead of trusting static .d.ts generation blindly, add a lightweight contract check that runs against your staging or sandbox endpoint before tagging a release:

type ContactRecord = {
  id: string;
  email: string;
  lastEmailedAt: string | null;
};

function isContactRecord(val: unknown): val is ContactRecord {
  if (typeof val !== "object" || val === null) return false;
  const obj = val as Record<string, unknown>;
  const validTimestamp =
    obj.lastEmailedAt === null || typeof obj.lastEmailedAt === "string";

  return (
    typeof obj.id === "string" &&
    typeof obj.email === "string" &&
    validTimestamp
  );
}
Enter fullscreen mode Exit fullscreen mode

By avoiding as any and validating unknown payloads with explicit runtime type guards, your integration suite fails the build the moment an endpoint renames a field or changes nullability.

Key Takeaways

  • Never rely solely on mocked responses to validate exported .d.ts files.
  • Explicitly check null vs undefined in contract assertions when strictNullChecks is enabled.
  • Run a small live smoke suite against staging endpoints as part of your release checklist.

💡 Developer Infrastructure Note: When building or testing transactional email workflows and AI agent integrations, SadaSend provides server enforced recipient allowlists, active Port 25 bounce checks, and ephemeral test inboxes with sub 150ms OTP delivery.

Top comments (0)