Introduction
expect-status replaces your per-status if/else boilerplate with a single, type-safe call. Zero runtime dependencies.
Before & after
Section titled “Before & after”const res = await api.acceptInvite({ body: { token } })
if (res.status === 200 || res.status === 201) {return res.body as Membership // unsafe cast}if (res.status === 409) {return redirect(`/org/${(res.body as any).orgId}`) // as any}if (res.status === 422) {throw new Error((res.body as any).message) // as any}// 401? 403? 429? 500? Hopefully we didn't miss one...throw new Error('Something went wrong')const membership = await expectStatus( [200, 201], api.acceptInvite({ body: { token } }), { 409: ({ orgId }) => redirect(`/org/${orgId}`), // body typed 422: 'Please check your input.', // auto-throws '5xx': 'Service unavailable.', // catch class },)// membership: Membership — zero casts, zero missed statusesFeatures
Section titled “Features”| Capability | How |
|---|---|
| Type narrowing | Return type is the body of the matched branch — not unknown, not the full union |
| Flat dispatch | { 409: fn, 422: "msg" } — functions are handlers, strings throw with that message |
| Ranges & groups | '4xx', '5xx', 'success', 'error', custom groups like 'auth' |
| Negation | '!4xx' — anything except client errors |
| Returning handlers | Handlers can return values, widening the return type |
| Adapter | Normalize Axios, custom envelopes, or any non-standard shape |
| Instance defaults | createExpectStatus with shared messages, hooks, and error class |
| Observability | onError / onSuccess hooks for Sentry, logging, metrics |
| Recover & transform | Catch-all error fallback and success body reshaping |
| SafeResult | throws: false returns { ok, data, error } instead of throwing |
| Exhaustive checking | exhaustive: true — TypeScript flags uncovered error statuses |
| Message bubbling | Unhandled errors extract body.message, RFC 7807 detail, and more |
Get started
Section titled “Get started”→ Quick Start — install, understand the response shape, and start coding