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

What is the purpose of .default(...) ? #51

Closed
dimatakoy opened this issue Aug 18, 2023 · 2 comments
Closed

What is the purpose of .default(...) ? #51

dimatakoy opened this issue Aug 18, 2023 · 2 comments

Comments

@dimatakoy
Copy link
Contributor

My concern is that anything can be put in it and the value will not be validated according to the given rules.

What is it for and is it needed now?

@dimatakoy
Copy link
Contributor Author

dimatakoy commented Aug 18, 2023

Now it turns out that the library insuring against runtime errors doesn't help us. I think default must respect validations.

console.log(v.string().assert(value => value.length > 10).default(1).parse(undefined)); // 1
console.log(v.number().default(1).parse()); // 1

// Imagine that i have `userRole` in `schemas.ts` and in other file i adding fallback if value is undefined. Then i change union literals, but default in other file keeps old value.
const userRole = v.union(v.literal('admin'), v.literal('user')).default('waiter');
console.log(userRole.try(undefined /* runtime value that was OK previously */));

@jviide
Copy link
Contributor

jviide commented Aug 18, 2023

The purpose of default is to allow undefined (or a missing value), and to replace undefined with a default value. It is comparable to the following scenarios elsewhere in JavaScript/TypeScript:

const { value=1 } = { value: undefined };
// value is now 1

function f(value=1) {
  return value;
}
f(); // 1
f(undefined); // 1

Like with all other Type methods (.optional(), .map(), ...) the order matters. If you want the type assertions to apply to .default() then add the type assertions. It would be more surprising if .default() was the exception. In itself it keeps the type safety, as it adds the default value's type to the output types.

@jviide jviide closed this as completed Aug 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants