Type Guards
Type guards are utility functions that allow you to safely identify and narrow the type of an unknown error payload at runtime.
Because JavaScript's try/catch blocks treat errors as unknown, you must verify the type of an error before accessing specific properties (like .details or .issues). This library provides three essential type guards.
isValidationError
Checks if an error is strictly an instance of the ValidationError class using the native JavaScript instanceof operator.
function isValidationError(err: unknown): err is ValidationError
Usage
import { isValidationError, fromError } from 'zod-validation-error';
try {
// some logic
} catch (err) {
const parsed = fromError(err);
if (isValidationError(parsed)) {
console.log(parsed.details); // TypeScript knows this is safe
}
}
isValidationErrorLike
Checks if an error resembles a ValidationError using heuristics rather than a strict instanceof check.
function isValidationErrorLike(err: unknown): err is ValidationError
Why use heuristics? (The Duplicate Dependency Problem)
In modern JavaScript ecosystems, especially within Monorepos (Yarn Workspaces, Nx, Lerna) or micro-frontends, npm and yarn can sometimes resolve dependencies in a way that installs multiple, different versions of zod-validation-error deep in your node_modules tree.
When this happens, an error thrown by "Version A" of the library will fail an instanceof check against the ValidationError class imported from "Version B" of the library, because their prototype chains are entirely different in memory.
isValidationErrorLike safely bypasses this by checking the object shape and the .name property (err.name === 'ZodValidationError').
Best Practice: If you are uncertain about your dependency tree, always prefer isValidationErrorLike.
isZodErrorLike
Checks if an error resembles a native Zod Error, again using heuristics to bypass prototype chain issues with the zod dependency.
function isZodErrorLike(err: unknown): err is zod.ZodError
Usage
This is incredibly useful if you want to inspect a raw error before passing it to zod-validation-error.
import { z as zod } from 'zod';
import { isZodErrorLike, fromZodError, fromError } from 'zod-validation-error';
try {
mySchema.parse(data);
} catch (err) {
// Safely check if it's a ZodError, avoiding prototype clashes
if (isZodErrorLike(err)) {
// It's safe to use the strict fromZodError here
const validationError = fromZodError(err);
return res.status(400).send(validationError.message);
}
// It's a different kind of error
const genericError = fromError(err);
return res.status(500).send(genericError.message);
}