Correctly infer type with transform and composite? #1241
-
I try to use transform and composite together: const SerializedCompactSchema =
Type.Transform(
Type.Object(
{
k: KindCompactSchema,
},
{ additionalProperties: true }
)
)
.Decode((value) => ({ compactKind: value.k }))
.Encode((value) => ({ k: value.compactKind }));
export const SerSchema =
Type.Composite([
SerializedCompactSchema
]);
type Ser = Static<typeof SerSchema>; which results in Thanks for you awesome work! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
@m1212e Hi, You can try the following. The Composite type may prove to be an issue here as Composite needs to rebuild an Object type and may discard interior Transforms. The reason is because compositing objects may invalidate the transform logic applied to the interior type. The constraints Instead you can try use a Intersect (but you will want to remove the additionalProperties constraint from Object and apply a unevaluatedProperties to the Intersect) import { Type, Static, StaticEncode, StaticDecode } from '@sinclair/typebox'
const KindCompactSchema = Type.Object({
k: Type.String()
})
const SerializedCompactSchema = Type.Transform(Type.Object({
k: KindCompactSchema,
}))
.Decode((value) => ({ compactKind: value.k }))
.Encode((value) => ({ k: value.compactKind }))
// Use Intersect (Composite discards Transforms as it needs to rebuild a new Object)
export const SerSchema = Type.Intersect([
SerializedCompactSchema
], { unevaluatedProperties: false })
// Use StaticEncode / StaticDecode to infer either Transform state.
type Ser = StaticDecode<typeof SerializedCompactSchema>;
type Ser = StaticEncode<typeof SerializedCompactSchema>; Also, you can use Hope this helps |
Beta Was this translation helpful? Give feedback.
@m1212e Hiya,
Ah right. I think the only way to really achieve this to apply the Transform to the composited type. The issue is that Composite only merges the
properties
of each sub type, and ignores the transform and other constraints applied for each sub type. The return type for Composite is a brand new Object, so any constraints and transforms need to be re-applied.A refactor of the types is probably the best way forward.