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

fix(validation-errors): type inference for branded, nullable, optional and array types #284

Merged
merged 2 commits into from
Oct 22, 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
11 changes: 7 additions & 4 deletions packages/next-safe-action/src/validation-errors.types.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
import type { Infer, InferIn, Schema } from "./adapters/types";
import type { Prettify } from "./utils.types";

// Basic types and arrays.
type NotObject = number | string | boolean | bigint | symbol | null | undefined | any[];

// Object with an optional list of validation errors.
type VEList = Prettify<{ _errors?: string[] }>;

// Creates nested schema validation errors type using recursion.
type SchemaErrors<S> = {
[K in keyof S]?: S[K] extends object | null | undefined ? Prettify<VEList & SchemaErrors<S[K]>> : VEList;
[K in keyof S]?: S[K] extends NotObject ? VEList : Prettify<VEList & SchemaErrors<S[K]>>;
} & {};

/**
* Type of the returned object when validation fails.
*/
export type ValidationErrors<S extends Schema | undefined> = S extends Schema
? Infer<S> extends object
? Prettify<VEList & SchemaErrors<Infer<S>>>
: VEList
? Infer<S> extends NotObject
? VEList
: Prettify<VEList & SchemaErrors<Infer<S>>>
: undefined;

/**
Expand Down