Cleaning on a per schema level? #809
-
Hi, I'm using a generator to generate typebox schemas from other parts of my project. I was wondering if it is somehow possible to not only allow additional properties on a per schema level, but also to define the cleaning behavior in that regard: Did you every consider something like this, or is this even possible? Thanks very much for you work! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@m1212e Hi I'm not sure there's much I can do to make TypeBox optionally Clean internally (not without depending on library specific schema keywords, which I'd like to avoid), but you can implement this functionality externally. import { Type, TSchema } from '@sinclair/typebox'
import { Value } from '@sinclair/typebox/value'
export function Clean(schema: TSchema, value: unknown): unknown {
return schema.cleanAdditionalFields === true ? Value.Clean(schema, value) : value
}
const A = Type.Object({
x: Type.Number(),
y: Type.Number(),
z: Type.Number()
}, {
cleanAdditionalFields: true
})
const B = Type.Object({
x: Type.Number(),
y: Type.Number(),
z: Type.Number()
})
console.log(Clean(A, { x: 1, y: 2, z: 3, w: 4 })) // { x: 1, y: 2, z: 3 }
console.log(Clean(B, { x: 1, y: 2, z: 3, w: 4 })) // { x: 1, y: 2, z: 3, w: 4 } The Value.* operations are intended to be combined and rearranged in lots of different of ways, and TypeBox isn't very opinionated as to how these functions are ultimately used. Creating a custom Clean function with schema dependent rules applied is inline with general anticipated usage of these functions though. Does this help? |
Beta Was this translation helpful? Give feedback.
@m1212e Hi
I'm not sure there's much I can do to make TypeBox optionally Clean internally (not without depending on library specific schema keywords, which I'd like to avoid), but you can implement this functionality externally.