fetchdts
A suite of type utilities for building strongly-typed APIs
🚧 Under active development
Features
- 💪 Strongly-typed query, body, headers, response.
- 🗺️ Static path segments, as well as dynamic and wildcard parameters.
- 📦 Exposes core utilities for building typed fetch functions.
Usage
Install package:
# npm
npm install fetchdts
# pnpm
pnpm install fetchdts
Quick Start
Define your API schema and create a strongly-typed fetch function:
import type { DynamicParam, Endpoint, TypedFetchInput, TypedFetchRequestInit, TypedFetchResponseBody, TypedResponse } from 'fetchdts'
// Define your API schema
interface APISchema {
'/users': {
[Endpoint]: {
GET: {
response: { id: number, name: string }[]
}
POST: {
body: { name: string, email: string }
response: { id: number, name: string, email: string }
}
}
[DynamicParam]: { // matches /users/123
[Endpoint]: {
GET: {
response: { id: number, name: string, email: string }
}
DELETE: {
response: { success: boolean }
}
}
}
}
}
// Create your typed fetch function
async function api<T extends TypedFetchInput<APISchema>>(
input: T,
init?: TypedFetchRequestInit<APISchema, T>,
) {
return fetch(input, init as RequestInit) as unknown as Promise<TypedResponse<TypedFetchResponseBody<APISchema, T>>>
}
// Use with full type safety
const users = await api('/users').then(r => r.json()) // Type: { id: number; name: string }[]
const user = await api('/users/123').then(r => r.json()) // Type: { id: number; name: string; email: string }
Core Concepts
Schema Definition
Your API schema describes the structure of your endpoints using TypeScript interfaces:
interface Schema {
'/path': {
[Endpoint]: {
[HTTPMethod]: {
query?: { param: string } // Query parameters
body?: { data: any } // Request body
headers?: { auth: string } // Required headers
response: { result: any } // Response data
responseHeaders?: { 'x-rate-limit': string } // Response headers
}
}
}
}
Path Types
Static Paths: Exact string matches
interface Schema {
'/api/users': {
[Endpoint]: {
GET: { response: User[] }
}
}
}
Dynamic Parameters: Single path segments
interface Schema {
'/api/users': {
[DynamicParam]: { // matches /api/users/123, /api/users/abc, etc.
[Endpoint]: {
GET: { response: User }
}
}
}
}
Wildcard Parameters: Zero or more path segments
interface Schema {
'/api': {
[WildcardParam]: { // matches /api, /api/anything, /api/nested/deep
[Endpoint]: {
GET: { response: any }
}
}
}
}
Matching order: a static segment is preferred to a dynamic parameter, and a dynamic parameter to
a wildcard, as in a router. Where the more specific match does not answer the method being
requested, the less specific one is used, so a POST-only static route and a GET wildcard sibling
are both reachable at the same path:
interface Schema {
'/api/blog': {
'/thing': { [Endpoint]: { POST: { response: D } } }
[WildcardParam]: { [Endpoint]: { GET: { response: C } } }
}
}
type A = TypedFetchResponseBody<Schema, '/api/blog/thing', 'POST'> // D
type B = TypedFetchResponseBody<Schema, '/api/blog/thing', 'GET'> // C
A query string, a fragment and a trailing slash are ignored when a path is resolved, so
'/api/users?page=2' resolves as '/api/users' does.
Symbols Reference
fetchdts uses special symbols to define different types of route matching:
import { DynamicParam, Endpoint, WildcardParam } from 'fetchdts'
interface Schema {
// Endpoint: Marks where HTTP methods are defined
[Endpoint]: {
GET: { response: Data }
POST: { body: Input, response: Data }
}
// DynamicParam: Matches a single path segment (e.g. the `123` of /users/123)
[DynamicParam]: {
[Endpoint]: {
GET: { response: User }
}
}
// WildcardParam: Matches the rest of the path, which may be empty (e.g. the `a/b.txt` of /files/a/b.txt)
[WildcardParam]: {
[Endpoint]: {
GET: { response: File }
}
}
}
HTTP Methods
All standard HTTP methods are supported:
GET, POST, PUT, DELETE, PATCH
OPTIONS, HEAD, CONNECT, TRACE
Methods may be written in either case ('POST' or 'post'), as a router compares them
case-insensitively. A route registered for GET also answers HEAD, as it does in h3, which serves
the GET handler and discards the body; an endpoint that registers HEAD itself is used in
preference.
interface RESTSchema {
'/api/users': {
[Endpoint]: {
GET: { response: User[] }
POST: { body: CreateUser, response: User }
}
[DynamicParam]: {
[Endpoint]: {
GET: { response: User }
PUT: { body: UpdateUser, response: User }
PATCH: { body: Partial<UpdateUser>, response: User }
DELETE: { response: { success: boolean } }
}
}
}
}
API Reference
Core Types
TypedFetchInput<Schema>
Extracts valid URL paths from your schema:
type ValidPaths = TypedFetchInput<APISchema>
// Result: '/users' | '/users/${string}'
A parameter is a ${string} placeholder, and ${string} may contain a slash, so a member covering a
parameter is a pattern that also matches a path with extra segments: '/users/1/2' is assignable to
`/users/${string}`. The union is what gives an editor its completions; ValidFetchInput is what
rejects a path the schema does not resolve.
AnyFetchPath
The shape any path may take, for use as the constraint of the type parameter a path is inferred into:
declare function $fetch<T extends AnyFetchPath>(input: T /* ... */): unknown
Constrain to this rather than to string, which loses the path of useFetch(ref('/api/users')):
ref() and computed() infer their own type parameter from the argument, and a literal widens where
the type it is inferred into is constrained by string and keeps its literal type where the
constraint is a pattern. A direct literal, a getter and a pre-declared Ref<'/api/users'> are
unaffected either way, and a union of paths has the same effect as a pattern, so a signature
constrained to TypedFetchInput<Schema> does not need this as well.
ValidFetchInput<Schema, Path, Method?>
Whether a path resolves, for use in parameter position:
declare function $fetch<T extends AnyFetchPath, M extends AnyHTTPMethod = 'GET'>(
input: T & ValidFetchInput<Schema, T, M>,
init?: TypedFetchRequestInit<Schema, T, M> & { method?: M },
): TypedFetchResponseBody<Schema, T, M>
This is an alternative to constraining the input with TypedFetchInput, which materialises the
union of every path in the schema. Validating one path costs no more than its depth, where checking
a union costs the size of the schema, so on a large generated schema this is substantially cheaper:
at 1500 routes and 200 call sites it checks in around 0.4s where the union takes around 3s
(pnpm bench --routes 1500 --calls 200 [--valid-input]