defineError
Defines a callable error constructor from an object or a function. Every call uses createError to create a fresh native Error with a stack.
Usage
Static definitions
Pass an object for an error that takes no arguments:
Function definitions
Pass a function when the message or custom fields depend on input. Its parameters become the constructor's parameters, including optional and rest parameters.
Inline definitions infer literal names. If you declare the builder separately, preserve its literal name with as const or an explicit return type. A name that has already widened to string cannot discriminate an error union.
The builder runs once per constructor call, not when defineError is called. Keep it pure. It returns exactly the object you would pass to createError; there are no per-field callback rules.
Explicit output and input contracts
Use ErrorWith to declare the output. For function definitions, the second generic is the argument tuple:
Static definitions need only the output generic:
These contracts are checked, not cast. Missing fields, wrong names, and incompatible argument types fail typechecking.
Parameters
A static error definition or a function returning one. Definitions require string name and message, accept optional cause, and can include custom data.
Returns
A function returning a native error with the inferred or explicit output type. Static definitions produce zero-argument functions; builder definitions preserve the builder's arguments.
Call it normally, without new. Match errors by their literal name, not instanceof notFound. Custom fields are shallowly copied and readonly in TypeScript, not frozen at runtime. Builder exceptions propagate normally; use attempt around unsafe work rather than hiding it in a definition.
See also
createError— create a one-off errorErrorWith— declare the output typeerr— wrap the instance in a failed Result- Result & Errors — match typed error variants