Types Plugin
The @hedystia/types package provides standalone type generation for use with any web framework. This allows you to get Hedystia's powerful type inference with Express, Hono, Fastify, or any other framework.
Installation
bun add @hedystia/typesWhy Use Hedystia Types?
- Type-safe clients — Generate a fully-typed client that mirrors your API
- Framework-agnostic — Works with any framework
- IDE autocomplete — Full IntelliSense support
- Type inference — Automatic inference from your route definitions
- No runtime overhead — Pure TypeScript definitions
Basic Usage
Define your routes as plain objects and generate types:
import { generateTypes } from '@hedystia/types'
const routes = [
{
method: 'GET',
path: '/users/:id',
params: { id: 'number' },
response: { id: 'number', name: 'string', email: 'string' },
},
{
method: 'POST',
path: '/users',
body: { name: 'string', email: 'string' },
response: { id: 'number', name: 'string', email: 'string' },
},
]
// Generate TypeScript definition file
await generateTypes(routes, './api.d.ts')With Express
Set up Express routes and generate types:
// server.ts
import express from 'express'
import { generateTypes } from '@hedystia/types'
const routes = [
{
method: 'GET',
path: '/api/posts/:id',
params: { id: 'number' },
response: { id: 'number', title: 'string', content: 'string' },
},
]
await generateTypes(routes, './api.d.ts')
const app = express()
app.get('/api/posts/:id', (req, res) => {
res.json({ id: 1, title: 'Hello', content: 'World' })
})
app.listen(3000)Then use with the Hedystia client:
// client.ts
import { createClient } from '@hedystia/client'
type AppRoutes = [
{ method: 'GET'; path: '/api/posts/:id'; response: { id: number; title: string; content: string } }
]
const client = createClient<AppRoutes>('http://localhost:3000/api')
const { data } = await client.posts.id(1).get()
console.log(data?.title) // Fully typed!With Hono
Use with Hono's lightweight runtime:
// server.ts
import { Hono } from 'hono'
import { generateTypes } from '@hedystia/types'
const routes = [
{
method: 'GET',
path: '/users',
response: [{ id: 'number'; name: 'string' }],
},
{
method: 'POST',
path: '/users',
body: { name: 'string'; email: 'string' },
response: { id: 'number'; name: 'string'; email: 'string' },
},
]
await generateTypes(routes, './types.d.ts')
const app = new Hono()
app.get('/users', (c) => {
return c.json([{ id: 1, name: 'Alice' }])
})
app.post('/users', async (c) => {
const body = await c.req.json()
return c.json({ id: 2, ...body })
})
export default appRoute Definition Format
interface RouteDefinition {
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
path: string
params?: Record<string, string | number | boolean>
query?: Record<string, string | number | boolean>
body?: any
headers?: Record<string, string>
response: any
data?: any
error?: any
}Type Inference
The generated types support full type inference:
type AppRoutes = [
{
method: 'GET'
path: '/users/:id'
params: { id: number }
query: { include?: 'posts' | 'comments' }
response: { id: number; name: string; email: string }
},
]
const client = createClient<AppRoutes>('http://localhost:3000')
// Full type safety
const { data } = await client.users.id(1).get({
query: { include: 'posts' }, // Autocomplete + validation
})
if (data) {
console.log(data.id) // ✓ Known
console.log(data.name) // ✓ Known
// console.log(data.unknown) // ✗ TypeScript error
}Advanced Patterns
Dynamic Route Generation
Generate types from your framework's routes:
import { generateTypes } from '@hedystia/types'
import { createServer } from './server'
const app = createServer()
// Extract routes from your framework and generate types
const routes = app.routes.map(route => ({
method: route.method,
path: route.path,
response: route.responseType,
}))
await generateTypes(routes, './api.d.ts')Build-Time Generation
Integrate type generation into your build process:
{
"scripts": {
"build:types": "bun build-types.ts",
"build": "bun build:types && bun build server.ts",
"dev": "bun build:types && bun --watch server.ts"
}
}// build-types.ts
import { generateTypes } from '@hedystia/types'
import routes from './routes'
await generateTypes(routes, './api.d.ts')
console.log('✓ Types generated')Benefits Over REST Documentation
- Compile-time safety — Catch typos and breaking changes at build time
- Automatic updates — Types always match your server
- No context switching — IDE autocomplete instead of API docs
- Refactoring — Rename endpoints and find all usages
- Team productivity — Frontend devs get instant feedback
Generate declarations in memory
import { generateTypesContent, generateTypes } from "@hedystia/types";
import { h } from "@hedystia/validations";
const routes = [{
method: "SUB", path: "/events",
data: h.object({ text: h.string() }),
message: h.object({ topic: h.string() }),
}];
const declaration = generateTypesContent(routes);
await generateTypes(routes, "./routes.d.ts");The content API returns the same AppRoutes declaration as the file API without writing to disk. Every route includes method and path. Schema sections are emitted only when supplied; raw undefined and null omit them. Paths, property keys and string literals are escaped into valid TypeScript. Unsupported schema conversions still emit any; review generated declarations when using other schema families.
Compact route declarations
The generator omits absent schema sections instead of inserting placeholder any fields. This applies to generateTypesContent, generateTypes and the server's buildTypes entry point.
import { generateTypesContent } from "@hedystia/types";
const declaration = generateTypesContent([{ method: "GET", path: "/health" }]);The declaration contains only:
export type AppRoutes=[{method:"GET";path:"/health"}];Raw undefined and null mean no schema. Explicit h.any(), h.unknown(), h.null(), h.undefined(), h.void() and h.never() remain present with their corresponding TypeScript types. Optional and nested schemas keep their existing meaning. Unsupported defined schemas still emit any; they are not discarded just because their conversion falls back to any.
The server keeps absent route schemas absent internally, preserves configured global request schemas when a route has no local replacement, and forwards declared subscription message schemas to the generator.
Client compatibility
Upgrade @hedystia/client together with regenerated declarations. The client interprets missing request sections as not declared, so it does not invent body, query or per-request headers options for them. Explicitly declare a schema to expose one of those options; h.any() provides a permissive contract when that is intentional. Global client transport headers can still be set through createClient options.
Missing response and error schemas are unknown, because absence of a schema does not prove that the server returns nothing. Narrow those values before accessing their properties. Undeclared path parameter types fall back to string | number, while declared parameter types remain enforced. Subscription data, errors and messages without schemas also default to unknown.
Existing full declarations with explicit any properties remain supported. This is a declaration-format and typing improvement; it does not change HTTP payloads or add a client runtime parser.
Swagger compatibility
Swagger uses the server's runtime route schemas, not erased .d.ts files. Absent request schemas do not create request-body or parameter sections, and an absent response schema leaves the required success response without a fabricated content schema. Explicit unconstrained schemas remain represented as {}. URL placeholders still become required string path parameters when no params schema is supplied, and configured global request schemas remain documented.
Declaration size comparison
Measured against the generator at commit f2604fb, using identical route paths and schemas before and after the change. Sizes include the generated-file header and use UTF-8 bytes. Gzip uses Node's default gzipSync settings; the measurements used Node 26.12.0 and zlib 1.3.2.
| Fixture | Before | Compact | Reduction | Gzip before | Gzip compact |
|---|---|---|---|---|---|
| Five HTTP routes | 783 B | 452 B | 42.27% | 257 B | 216 B |
| 1,000 routes without schemas | 118,952 B | 32,952 B | 72.30% | 3,016 B | 2,477 B |
| 1,000 routes with response schemas | 138,952 B | 65,952 B | 52.54% | 3,172 B | 2,746 B |
| One fully declared route | 181 B | 181 B | 0% | 151 B | 151 B |
The five-route fixture is the route set in Tests/server/build.test.ts. The synthetic fixtures use GET /items/0 through GET /items/999; the response-schema variant adds { id: number; name: string } to each route. The fully declared control uses POST /complete with all eight schema sections explicitly set to h.any() and therefore loses no fields.
For example, measure the schema-free fixture against each built version with:
import { gzipSync } from "node:zlib";
import { generateTypesContent } from "@hedystia/types";
const routes = Array.from({ length: 1000 }, (_, index) => ({
method: "GET",
path: `/items/${index}`,
}));
const content = generateTypesContent(routes);
console.log({ bytes: Buffer.byteLength(content), gzipBytes: gzipSync(content).byteLength });These are declaration-file savings, not browser JavaScript bundle savings or a compiler-speed benchmark. TypeScript types are erased from runtime code, and savings depend on how many schema sections your routes actually declare.
