Fondu

Type safety

View as Markdown

Fondu checks the seams between the server and the browser at compile time: what a route sends to a page, the URLs your pages link to, the input your handlers read, and what the browser sends to a .ts route with request() and gets back. Rename a prop, move a route or change a schema, and TypeScript points at every place that no longer fits, before anything runs.

Where the types come from

There is nothing to declare twice. Each type has one source, and the rest follows from it:

SourceChecks
a page component's propsrender(c, Page, props): every prop is there and fits
the files in app/routes/href('/users/:id', { id }): the URL exists, its params, its actions
a route's query schemahref('/search', { query }): the query the route takes
a handler's schemas (withValidator)the body, query and params the handler receives
a .ts route's handlersrequest(): the params, query and body it takes, and its answer
declarations next to your middlewareshare(), flash(), usePage(), c.get()

The dev server and the build write the routes' types into app/fondu.gen.d.ts as your files change; commit it.

Page props

The component is the source: its parameter's type is what render() takes for that page.

// app/routes/users/[id].tsx
export const loader = defineHandler(async (c) => {
  const user = await getUser(c.req.param('id'))
  return render(c, Show, { user }) // error: canEdit is missing
})

export default function Show({ user, canEdit }: { user: User; canEdit: boolean }) { … }

URLs

href() from fondu/client takes the URL patterns of app/routes/, and a route's actions as ?name:

href('/users/:id', { id: 7 }) // '/users/7'
href('/users/:id?rename', { id: 7 }) // '/users/7?rename': actions.rename
href('/users/:id') // error: the param is missing
href('/user/:id', { id: 7 }) // error: no such route

query and hash add a query string and a fragment. When the route checks its query with withValidator({ query }) (its loader, a .ts file's GET, or the action), query is typed by that schema; otherwise it takes any values.

// app/routes/search.tsx
const query = z.object({ q: z.string(), page: z.optional(z.coerce.number()) })
export const loader = defineHandler.withValidator({ query })(async (c, { query }) => …)

// anywhere
href('/search', { query: { q: 'ada', page: 2 }, hash: 'results' }) // '/search?q=ada&page=2#results'
href('/search') // error: the schema requires q
href('/users/:id', { id: 7, query: { tab: 'posts' } }) // '/users/7?tab=posts': no schema, any query

href() writes the query as withValidator({ query }) reads it: a list as tag[]=a (one item too), an object as user[name]=Ada, a list of objects or lists with indexes (rows[0][a]=1). Numbers and booleans are written as text (2, true) and read back as strings, so a schema parses them. An empty list or object is left out and reads back as absent: give such a field a default in its schema.

A param can't be named query or hash: they are href()'s (and method, body, headers and signal are request()'s). A value that is undefined or null is left out, and z.coerce.number() takes any value (a string or a number), as the URL carries it as text.

A redirect takes href() too: return c.redirect(href('/users/:id', { id: user.id }), 303).

Handler input

defineHandler.withValidator() types the handler's input from its schemas, as they parse it: with z.coerce.number(), params.id is a number.

const idParams = z.object({ id: z.coerce.number() })

export const loader = defineHandler.withValidator({ params: idParams })(async (c, { params }) => {
  params.id // number
})

Any Standard Schema library works: Forms and validation.

Calls to a route

request() from fondu/client is typed by the route file it calls. The path must be a .ts route of the app, its params are the ones href() takes, query and body are typed by the handler's withValidator schemas, and the answer is what the handler returns with c.json(), as JSON delivers it. Routes has the details.

Shared props, flash data and context values

What a middleware sets is typed where it is set, by declaring Hono's and Fondu's own interfaces:

// app/routes/_middleware.ts
declare module 'hono' {
  interface ContextVariableMap {
    user: User | null // c.set('user', …), c.get('user')
  }
}
declare module 'fondu' {
  interface Register {
    shared: { auth: { user: { name: string } | null } } // share(), usePage().props
    flash: { message?: string } // flash(), usePage().flash
  }
}

share() and flash() then take only those, and usePage() returns them. If render() overrides a shared prop, its value must fit both the page and the layout, even when the page accepts arbitrary keys. For a union, don't distinguish a branch by the absence of a shared key: middleware can add it. For example, if mode is shared as 'text' | 'count', use mode: 'text' and mode: 'count' on the two variants and pass the matching mode with their data.

What crosses as JSON

Props travel to the browser as JSON, so a page's prop types are what it receives: a Date arrives as a string, a Map or a Set as {}, and undefined fields are left out. render() checks both sides of that:

// app/routes/posts/[slug].tsx
export default function Show({ post }: { post: { title: string; publishedAt: string } }) { … }
render(c, Show, { post: { title, publishedAt: new Date() } }) // fine: JSON makes the Date a string

A page that types a prop as Date, Map, Set or a function is an error at render(), as the page would get something else. Anything with a toJSON() passes for what that returns.

Props from your data

A page declares its props, and render() checks every writer against them. To write that type once, from the type of the data, use AsJson<T> from fondu. It is T after the JSON round trip, the way a page receives it:

  • Date, or anything with toJSON(), becomes what that returns (a Date is a string).
  • undefined properties become optional, and undefined in an array becomes null.
  • Functions and symbols are left out of objects, and are null in arrays.
  • Map, Set and other objects with no own data become {}.
  • A bigint is a type error, as JSON.stringify throws on it.
  • Unions, tuples and readonly arrays keep their shape.

These rules are what AsJson guarantees. The exact shape of the error for a bigint is not part of it: it may change.

render() takes what becomes the page's type, so a page that declares AsJson<Row> gets a Row from the loader, with its Date. Nothing is converted by hand, and the page never types a Date.

A whole row

// app/routes/contacts.tsx
type Contact = AsJson<typeof contacts.$inferSelect>

export default function Contacts({ contacts }: { contacts: Contact[] }) { … }

Props are public, and a whole row sends every column. Use this for a table the page shows in full, and select columns for the rest.

A selected shape

Write the query as a function in the route file, and take the page's type from its result:

// app/routes/contacts.tsx
const listContacts = () =>
  db.select({ id: contacts.id, name: contacts.name, createdAt: contacts.createdAt }).from(contacts)

export const loader = defineHandler(async (c) =>
  render(c, Contacts, { contacts: await listContacts() }),
)

type Props = { contacts: AsJson<Awaited<ReturnType<typeof listContacts>>> }

export default function Contacts({ contacts }: Props) { … }

typeof listContacts is in a type position, so the browser's copy of the file does not keep the query (or db): Server and client. When an action or another route needs the query too, move it to a module named *.server.ts and import its type in the page with import type { listContacts } from …: that import is removed with the other types.

A form's values

For the values a form starts with, take the type from the form's schema. The action's body is already typed by withValidator.

type Values = z.infer<typeof newContactSchema>

export default function NewContact({ values }: { values: Values }) { … }

Where it stops

AsJson goes by the declared type. It can't tell that a getter of a class, or the message of an Error, is not own data: convert such a value before it is a prop. It needs a concrete type, as a bigint is found by looking inside it: for a type parameter T that is not resolved yet, TypeScript reports an error.

Setup

None beyond tsconfig.json: a new app has it, and ships app/fondu.gen.d.ts for its first route. Keep the file committed, so a fresh clone or CI has the types before the first build.

Without that file, href() and request() take no path: the error says Run vite dev or vite build to generate app/fondu.gen.d.ts. An app with no routes gets the same error.

A library, or a package with no app

A package that uses fondu/client without routes of its own opts out: any string is a path.

// types.d.ts
declare module 'fondu' {
  interface Register {
    routes: string
  }
}

Last updated