Skip to content

Generics with constrained parameters #957

Answered by sinclairzx81
dielsalder asked this question in Q&A
Discussion options

You must be logged in to vote

@dielsalder Hiya,

You can add an additional TIntersect constraint to the WithId function.

import { Type, TObject, TIntersect } from '@sinclair/typebox'

const WithId = <T extends TObject | TIntersect>(schema: T) =>
  Type.Intersect([
    schema,
    Type.Object({
      id: Type.String(),
    }),
  ]);

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.

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@dielsalder
Comment options

@sinclairzx81
Comment options

Answer selected by dielsalder
@dielsalder
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants