Comments (5)
@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.
Both Create and Default have been updated clone the default
annotation on assignment. Updates for both on 0.32.8.
Cheers
from typebox.
@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 thetype
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.
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.
@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)
- [BUG] Value.create caches the default date HOT 1
- Feature request: Value.Assert and TypeCheck.Assert HOT 3
- [Feature Request?] allow more flexible input for string pattern HOT 3
- Individual types imports naming conflict with native classes HOT 4
- Strict error: Unknown type HOT 2
- Maximum call stack size exceeded. HOT 2
- TUnion of literals from const array HOT 2
- "Value.Clean" doesn't work with Unions of objects with prohibited additionalProperties HOT 3
- JS floating point precision bug causes multipleOf validation to fail HOT 4
- Tuple with rest items (or Array with prefixedItems) HOT 2
- useDefaults HOT 3
- Support for discriminator HOT 1
- Support for self-referencing fields of recursive type HOT 2
- Property '[Kind]' is missing in type 'TObject' but required in type 'TObject<TProperties>' HOT 3
- [feat] Bail / Early Cancel Mode HOT 1
- Setting Description HOT 1
- Schema dependency using Typebox HOT 3
- Composite working uncorrect HOT 5
- Include `Value.Errors` array on thrown errors HOT 2
- Add JSON path tracking to Encode/Decode HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from typebox.