Generics with constrained parameters #957
-
Here's a minimal example of some existing ts types that I want to convert to typebox schemas:
The doc say to use
Is it possible to do this in typebox? Would appreciate any guidance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
@dielsalder Hi, The Type.Intersect type constituents need to be wrapped in a import { Type } from '@sinclair/typebox'
const WithName = Type.Object({ name: Type.String() });
const WithId = <T extends typeof WithName>(schema: T) => Type.Intersect([
schema,
Type.Object({
id: Type.String(),
})
]);
// ok, object has 'name' property
const A = WithId(Type.Object({ name: Type.String() })) // ok, has name
// ok, object has 'name' property + 'role' property
const B = WithId(Type.Object({ name: Type.String(), role: Type.String() }))
// error: object does not have 'name' property
const C = WithId(Type.Object({ role: Type.String() }))
So, while the above works, it's usually more common to constrain to import { Type, TObject } from '@sinclair/typebox'
const WithId = <T extends TObject>(schema: T) => Type.Intersect([
schema,
Type.Object({
id: Type.String(),
})
]); Hope this helps |
Beta Was this translation helpful? Give feedback.
@dielsalder Hiya,
You can add an additional TIntersect constraint to the WithId function.
Unfortunately, even though the Intersect type is structurally an Object type in this case, the TIntersect json schematics do not structurally extend TObject (even though in TypeScript this would be permissible). Because the json schema structures are different, you must specify a TIntersect in the generic constraint.