Skip to content

Commit

Permalink
feat: provide a default value to .optional()
Browse files Browse the repository at this point in the history
  • Loading branch information
GauBen committed Oct 19, 2024
1 parent 6b250a3 commit ab30d37
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/smooth-zebras-jam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"formgator": patch
---

Provide a default value to `.optional()`
1 change: 1 addition & 0 deletions src/definitions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ describe("methods", () => {
const data = new FormData();

assert.deepEqualTyped(text().optional()[safeParse](data, "input"), succeed(undefined));
assert.deepEqualTyped(text().optional("")[safeParse](data, "input"), succeed(""));
});

it("should accept present fields", () => {
Expand Down
7 changes: 5 additions & 2 deletions src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,11 @@ export interface FormInput<T = unknown> {
*
* It returns `undefined` instead of `null` to differentiate between a missing
* field (`undefined`) and a field with an empty value (`null`).
*
* You may provide a default value to be used when the field is missing.
*/
optional(): FormInput<T | undefined>;
optional<U>(value: U): FormInput<T | U>;

/** @private @internal */
[safeParse]: (data: ReadonlyFormData, name: string) => Result<T, ValidationIssue>;
Expand Down Expand Up @@ -153,11 +156,11 @@ function refine<T, U extends T>(
};
}

function optional<T>(this: FormInput<T>): FormInput<T | undefined> {
function optional<T, U>(this: FormInput<T>, value?: U): FormInput<T | U> {
return {
...this,
[safeParse]: (data, name) => {
if (!data.has(name)) return succeed(undefined);
if (!data.has(name)) return succeed(value as U);
return this[safeParse](data, name);
},
};
Expand Down

0 comments on commit ab30d37

Please sign in to comment.