You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I've been working on a project using the @sinclair/typebox library to define and validate data structures in Node.js. My main goal is to ensure that all objects, including nested ones, are filled with default values and correctly handle type conversions.
Here's the approach I've developed:
import{log}from'node:console';import{Type}from'@sinclair/typebox';import{TypeCompiler}from'@sinclair/typebox/compiler';import{Value}from'@sinclair/typebox/value';constT=Type.Object({userName: Type.Optional(Type.String()),loginAt: Type.Optional(Type.Number({default: Date.now()})),settings: Type.Object({language: Type.Optional(Type.Number({default: 1}))},{default: {}}),roles: Type.Array(Type.String(),{default: ['user']}),status: Type.Enum({one: 1,two: 2,three: 3},{default: 1})},{additionalProperties: false});constC=TypeCompiler.Compile(T);// this to be done once and reused for all checksconstval={userName: 123,};letV=Value.Default(T,Value.Clone(val));// fill missing valV=Value.Convert(T,V);// type conversionconstR=C.Check(V);// check errorconstE1=R ? C.Errors(V).First() : null;// 1st errorlog({value: V,error: E1});
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hello everyone,
I've been working on a project using the @sinclair/typebox library to define and validate data structures in Node.js. My main goal is to ensure that all objects, including nested ones, are filled with default values and correctly handle type conversions.
Here's the approach I've developed:
i t results in
this is serving the purpose for me.
I just wanted to ask whether this approach is good or I can further optimize it.
thanks
Beta Was this translation helpful? Give feedback.
All reactions