Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add isZodErrorLike description and usage example to README.md #378

Merged
merged 1 commit into from
Sep 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ Validation error: Number must be greater than 0 at "id"; Invalid email at "email
- [errorMap](#errormap)
- [isValidationError(error)](#isvalidationerror)
- [isValidationErrorLike(error)](#isvalidationerrorlike)
- [isZodErrorLike(error)](#iszoderrorlike)
- [fromError(error[, options])](#fromerror)
- [fromZodIssue(zodIssue[, options])](#fromzodissue)
- [fromZodError(zodError[, options])](#fromzoderror)
Expand Down Expand Up @@ -220,6 +221,39 @@ const invalidErr = new Error('foobar');
isValidationErrorLike(err); // returns false
```

### isZodErrorLike

A [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on _heuristics_ comparison.

_Why do we need heuristics since we can use a simple `instanceof` comparison?_ Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older `zod` version internally. In such case, the `instanceof` comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.
jmike marked this conversation as resolved.
Show resolved Hide resolved

#### Arguments

- `error` - error instance (required)

#### Example

```typescript
import { z as zod } from 'zod';
import { ValidationError, isZodErrorLike } from 'zod-validation-error';

const zodValidationErr = new ValidationError('foobar');
isZodErrorLike(zodValidationErr); // returns false

const genericErr = new Error('foobar');
isZodErrorLike(genericErr); // returns false

const zodErr = new zod.ZodError([
{
code: zod.ZodIssueCode.custom,
path: [],
message: 'foobar',
fatal: true,
},
]);
isZodErrorLike(zodErr); // returns true
```

### fromError

Converts an error to `ValidationError`.
Expand Down