Course contentsShow
← TypeScript
Lesson 1302 of 1,79630. Type-Safe APIsFree lesson

io-ts and Codec-Based Inference

How io-ts codecs simultaneously validate and provide types through the TypeOf helper.

io-ts and Codec-Based Inference

What you'll learn: How io-ts codecs serve double duty—validating data at runtime AND providing compile-time TypeScript types through a single schema definition.

The Dual-Purpose Codec Pattern

In io-ts, a codec is a reversible data structure that knows how to:

  1. Decode (validate and parse) external data at runtime
  2. Encode (serialize) TypeScript values back to a wire format
  3. Provide TypeScript types automatically through inference

Think of it like a two-way dictionary: it translates between the "outside world" (untyped JSON, API responses) and your "typed world" (TypeScript code), while simultaneously teaching TypeScript what shape to expect.

How Inference Works with TypeOf

Unlike Zod (where you infer types with z.infer<>), io-ts uses the TypeOf helper to extract compile-time types from runtime codecs:

import * as t from 'io-ts';

// Define the codec (runtime validation logic)
const UserCodec = t.type({
  id: t.number,
  name: t.string,
  email: t.string,
});

// Extract the TypeScript type from the codec
type User = t.TypeOf<typeof UserCodec>;
// User = { id: number; name: string; email: string; }

The codec UserCodec is a runtime value you can call methods on, but TypeOf reaches into TypeScript's type system to pull out the corresponding compile-time type.

Single Source of Truth

Because both validation logic and type definitions come from the same codec, you eliminate sync issues. Change t.number to t.string and both runtime checks and compile-time types update together:

const updatedCodec = t.type({
  id: t.string, // Changed here
});

type Updated = t.TypeOf<typeof updatedCodec>;
// Updated = { id: string } — type follows codec automatically

Key Takeaway: io-ts codecs are runtime validators that TypeScript can introspect through TypeOf, giving you compile-time types and runtime safety from a single schema definition—no duplication required.