Skip to content

Commit

Permalink
fix(types): readable ZodField type
Browse files Browse the repository at this point in the history
fixes #55
  • Loading branch information
MiroslavPetrik committed Dec 4, 2023
1 parent 63dbd4a commit af53ad7
Showing 1 changed file with 27 additions and 15 deletions.
42 changes: 27 additions & 15 deletions src/fields/zod-field/zodField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,31 +78,43 @@ export type OptionalZodField<
OptSchema extends z.Schema = ZodUndefined,
> = ZodField<Schema, OptSchema, WritableRequiredAtom>; // for OptionalZodField we can write false to the required atom

export type ZodField<
/**
* This is an alias to ZodField, it hides the 3rd argument from type tooltip.
*/
type RequiredZodField<
Schema extends z.Schema = ZodAny,
OptSchema extends z.Schema = ZodUndefined,
RequiredAtom = Atom<boolean>, // required field have read-only RequiredAtom
> = FieldAtom<Schema["_output"] | OptSchema["_output"]> extends Atom<
infer Config
> = ZodField<Schema, OptSchema>;

type ExtendFieldAtom<Value, State> = FieldAtom<Value> extends Atom<
infer DefaultState
>
? {
optional: () => OptionalZodField<Schema, OptSchema>;
} & Atom<
Config & {
required: RequiredAtom;
}
>
? Atom<DefaultState & State>
: never;

export const zodField = <
export type ZodField<
Schema extends z.Schema = ZodAny,
OptSchema extends z.Schema = ZodUndefined,
RequiredAtom = Atom<boolean>,
> = ExtendFieldAtom<
Schema["_output"] | OptSchema["_output"],
{ required: RequiredAtom }
> & {
optional: () => OptionalZodField<Schema, OptSchema>;
};

export function zodField<
Schema extends z.Schema,
OptSchema extends z.Schema = ZodUndefined,
>({
schema,
optionalSchema,
...config
}: ZodFieldConfig<Schema, OptSchema>): ZodField<Schema, OptSchema> => {
const requiredAtom = atom(true); // constant, unwritable when .optional() is not called
}: ZodFieldConfig<Schema, OptSchema>): RequiredZodField<Schema, OptSchema> {
/**
* Read-only atom for default zodFields which all are required.
*/
const requiredAtom = atom(true);

const baseFieldAtom = fieldAtom({
validate: zodValidate(
Expand Down Expand Up @@ -194,4 +206,4 @@ export const zodField = <
zodField.debugLabel = `zodField/${config.name ?? zodField}`;

return zodField;
};
}

0 comments on commit af53ad7

Please sign in to comment.