Course contentsShow
← TypeScript
Lesson 1533 of 1,79635. TypeScript with Framework Cross-ReferencesFree lesson

Hono's Type-Safe Request Context

Understanding Hono's Context<Env, Path, Input> and how it infers types from route patterns.

Hono's Type-Safe Request Context

What you'll learn: How Hono's Context<Env, Path, Input> type uses generics to infer route patterns, environment bindings, and request data types automatically.

The Problem Hono Solves

Unlike Express where req and res are loosely typed, Hono provides a context object (c) that knows exactly what route you're on, what parameters exist, what your environment variables are, and what shape your request body has—all at compile time.

The Context Generic Signature

Hono's context is typed as:

Context<Env, Path, Input>
  • Env: Your environment bindings (database connections, API keys, etc.)
  • Path: The literal route pattern string (e.g., "/users/:id")
  • Input: The shape of incoming data (params, query, body, headers)

How Type Inference Works

When you define a route in Hono, the framework extracts type information from the route pattern itself:

// Hono infers that 'id' exists in params from the pattern
app.get('/users/:id', (c) => {
  // c.req.param('id') is typed as string, not string | undefined
  const userId = c.req.param('id')
  // TypeScript knows this parameter exists!
})

The Path generic captures the literal route string, and Hono's internal conditional types extract parameter names like :id, making them available with full autocomplete.

Why This Matters

Instead of type assertions or manual annotations on every route, the route pattern string becomes the single source of truth. Change "/users/:id" to "/users/:userId" and TypeScript immediately flags incorrect property access throughout your handler.

Key Takeaway: Hono's Context<Env, Path, Input> generics turn route patterns into compile-time contracts, inferring parameter names, types, and request shapes directly from your route definitions—giving you Express-like ergonomics with end-to-end type safety.