How to rename a field? #741
Replies: 1 comment
-
@alexgorbatchev Hi, You're on the right track and this is the recommended way to implement this functionality. Just keep in mind TypeBox is somewhat different to other libraries in that it mandates that transforms are implemented as bi-directional codecs (so you need to explicitly state how you want to decode AND encode the value). Frameworks that use TypeBox can use the codec to automatically decode and encode values for you. import { Type } from '@sinclair/typebox'
import { Value } from '@sinclair/typebox/value'
const T = Type.Transform(Type.Object({
a: Type.Number(),
b: Type.Number(),
c: Type.Number()
})).Decode(value => ({ // (a, b, c) -> (x, y, z)
x: value.a,
y: value.b,
z: value.c
})).Encode(value => ({ // (x, y, z) -> (a, b, c)
a: value.x,
b: value.y,
c: value.z,
}))
const R = Value.Decode(T, { a: 1, b: 2, c: 3 })
console.log(R) // { x: 1, y: 2, z: 3 } The implementation of transforms can be clunky and do require careful programming. However once the transform is created (and tested with Decode and Encode), you can use it everywhere. You usually want to reserve transforms for use in a select few types (usually things that cannot be serialized in Json and need decoding before use (i.e. Dates, Buffers)), but renaming properties is also a valid usage. The explicit mapping from one type to another is an "exceptional" case, so some of the verbosity is warranted here (as it makes it explicitly clear there is a remapping layer between the data you receive the data your application sees) Hope this helps. |
Beta Was this translation helpful? Give feedback.
-
Just started learning TypeBox and I'm struggling to figure out how to rename a field. I got this to work, but this feels way to clunky to be the recommended approach.
Beta Was this translation helpful? Give feedback.
All reactions