Coder Social home page Coder Social logo

Create missing default about typebox HOT 5 CLOSED

wenerme avatar wenerme commented on June 5, 2024
Create missing default

from typebox.

Comments (5)

sinclairzx81 avatar sinclairzx81 commented on June 5, 2024 2

@wenerme Hiya,

the default on schema changed

Ah yes, I see it. This is indeed a bug (as schematics are treated as immutable). Will look at fixing this over the next few days. Good find!

BTW, I also want to a easier way to parse existing, is this right ?

Yes, this code is correct. Combined these functions and would constitute a Parse operation.

const Parse = <T extends TSchema>(T: T, value: unknown) => 
  Value.Decode(T,
    Value.Clean(T,
      Value.Default(T,
        Value.Convert(T, value),
      )
    )
  )

const value = Parse(Type.String(), 'hello world')

from typebox.

sinclairzx81 avatar sinclairzx81 commented on June 5, 2024 2

@wenerme

Both Create and Default have been updated clone the default annotation on assignment. Updates for both on 0.32.8.

Cheers

from typebox.

sinclairzx81 avatar sinclairzx81 commented on June 5, 2024

@wenerme Hi,

The Create and Default functions have different semantics when instancing values.

Create

  • Creates values derived from type information.
  • Will throw if value cannot be instanced.
  • Schema default annotations are optional (will override the type if specified)
  • Returns a static type

Default

  • Patches values derived from default annotations only
  • Will not throw if value cannot be instanced.
  • Schema default annotations are required
  • Returns unknown

These functions are the inverse of each other and are used different ways. The Create function is used when you want a NEW value instanced. The Default function is used when you want to PATCH an existing value for missing properties (usually used prior to a validation check to instance sub properties of that value).

Ref: Default has similar characteristics to Ajv useDefaults

https://ajv.js.org/options.html#usedefaults


Mutability

The Default, Clean and Mutate functions are all documented as mutable functions (as well as commented as [Mutable]). This is intentional and primarily done to boost performance in validation pipelines and avoid unnecessary instancing of JavaScript objects (which is very slow). From the readme.

Use Default to generate missing properties on a value using default schema annotations if available. This function does not check the value and returns an unknown type. You should Check the result before use. Default is a mutable operation. To avoid mutation, Clone the value first.

So, to avoid mutation, you should clone the value (which is a opt-in performance cost)

const D = Value.Default(T, Value.Clone({})) // To avoid mutation, clone the value.

Hope this helps
S

from typebox.

wenerme avatar wenerme commented on June 5, 2024

for console.log(Value.Default(T, {})); I mean

  const T = Type.Object({
    a: Type.Object({
      b: Type.Array(Type.String(), { default: [] }),
    }, { default: {} }),
  });
  (Value.Default(T, {}) as any).a.b.push('1')
  console.log(Value.Default(T, {})); // the default on schema changed

I use zod before, so I try to find parse in typebox, zod parse do not mutate(that's also a problem, some time want to mutate the input), so I think muatte Value.Default(T, {}) result is ok, which is not.


BTW, I also want to a easier way to parse existing, is this right ?

  const T = Type.Object({
    n: Type.Number(),
    d: Type.Date(),
    a: Type.Object({
      b: Type.Array(Type.String(), { default: [] }),
    }, { default: {} }),
  });

console.log(
    // get T, run transform
    Value.Decode(T,
      // remove additional
      Value.Clean(T,
        // add missing
        Value.Default(T,
          // '1' -> 1
          Value.Convert(T, {
            z: 1, n: '1', d: new Date(),
          }),
        ),
      ),
    ),
  );

from typebox.

sinclairzx81 avatar sinclairzx81 commented on June 5, 2024

@wenerme Heya,

Have quickly patched this on 0.32.7. If you want to give this a quick test your side, can look to close off this issue.

Thanks for reporting this, it's a excellent catch!

Cheers

from typebox.

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.