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

Should getDefaults be equivalent to v.parse (Schema, undefined)? #1039

Closed
wszgrcy opened this issue Jan 29, 2025 · 1 comment
Closed

Should getDefaults be equivalent to v.parse (Schema, undefined)? #1039

wszgrcy opened this issue Jan 29, 2025 · 1 comment
Assignees
Labels
question Further information is requested

Comments

@wszgrcy
Copy link

wszgrcy commented Jan 29, 2025

import * as v from 'valibot';

(() => {
  const OptionalEntrySchema = v.optional(
    v.object({
      k1: v.optional(
        v.object({
          k2: v.optional(v.string(), 'value2'),
        }),
        {}
      ),
    }),
    {}
  );
  let b = v.parse(OptionalEntrySchema, undefined);
  console.log(b); // { k1: { k2: 'value2' } }
  console.log(v.getDefaults(OptionalEntrySchema)); //{}
})();

I think there should be a method to obtain the default value of a schema after parsing, so I used 'getDefaults'. However, this method can only obtain the default value of one layer of object and cannot recursively obtain it.
Should we add a separate function implementation or do we currently have no development plan for this?

@fabian-hiller
Copy link
Owner

Does this work for you? Here is a playground to execute the code.

import * as v from 'valibot';

const OptionalEntrySchema = v.object({
  k1: v.object({
    k2: v.optional(v.string(), 'value2'),
  }),
});

console.log(v.getDefaults(OptionalEntrySchema));

getDefaults will return any defined defaults, and if not, will recursively resolve defaults over objects and tuples. But right now it can't resolve optional objects without defaults because we can't know if the user wants it to return undefined or check for the wrapped schema and continue. This could be solved. It would be great to get more feedback on this. For now, you could also copy the source of getDefaults and modify it to your needs.

@fabian-hiller fabian-hiller self-assigned this Jan 30, 2025
@fabian-hiller fabian-hiller added the question Further information is requested label Jan 30, 2025
@wszgrcy wszgrcy closed this as completed Jan 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants