Coder Social home page Coder Social logo

Comments (2)

dimatakoy avatar dimatakoy commented on May 22, 2024

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 */));

from valita.

jviide avatar jviide commented on May 22, 2024

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.

from valita.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.