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

When to Explicitly Annotate vs Purely Infer

Trade-offs between letting validators drive all types versus explicitly typing some shapes for clarity.

When to Explicitly Annotate vs Purely Infer

You'll learn when to write explicit types alongside schema validators versus letting TypeScript infer everything from your schemas automatically.

The Core Tension

When you're working with validator libraries like Zod, you face a choice: should you infer types from your schemas using utilities like z.infer<typeof schema>, or should you write explicit interfaces and use them to guide your schemas?

Both approaches work, but they have different trade-offs:

Pure inference means your schema is the single source of truth. Types flow automatically from your runtime validation logic. You never duplicate structure.

Explicit annotation means writing out the TypeScript type first, then building a schema that matches it. This gives you named types, clearer errors, and better documentation — but risks drift between your type and your validator.

When Explicit Annotation Helps

Sometimes you want a named, reusable type that appears in error messages and IDE hints:

// Explicit type for clarity
interface UserProfile {
  id: string;
  email: string;
  age: number;
  roles: Array<'admin' | 'user'>;
}

// Schema validates the shape we documented
// (but nothing enforces they match!)

This approach shines when:

  • The type appears in many function signatures across your codebase
  • You want self-documenting API contracts
  • Error messages benefit from seeing "UserProfile" instead of a complex inferred shape
  • You're building a library where exported types matter

When Pure Inference Wins

With pure inference, the schema drives everything:

const userSchema = z.object({
  id: z.string(),
  email: z.string().email(),
  age: z.number().min(0),
  roles: z.array(z.enum(['admin', 'user']))
});

type UserProfile = z.infer<typeof userSchema>;

Now there's zero chance your type and validator disagree. The schema is truth. Types follow automatically.

This wins when:

  • Runtime validation is the primary concern
  • Schema changes happen frequently
  • You want guaranteed synchronization
  • The type is only used locally

The Hybrid Middle Ground

Many teams use both: explicit types for public APIs (what consumers see), inferred types for internal validation (what actually gets checked).

Key Takeaway: Use pure inference when the schema is your source of truth and changes frequently. Use explicit annotations when named types improve clarity and the shape is stable. Never maintain both manually — pick one to follow the other.