Skip to content

Simulate inheritance #625

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

You must be logged in to vote

@Ghirigoro Hi,

You can use either Type.Intersect() or Type.Composite() to extend a base type. The example below extends using Composite.

TypeScript Link Here

import { Type, Static } from '@sinclair/typebox'

const Base = Type.Object({
  id: Type.String(),
  elements: Type.Array(Type.Object({
    type: Type.String()
  }))
})

const Derived = Type.Composite([Base, Type.Object({
  id: Type.Literal('B'),
  elements: Type.Array(Type.Union([ // Used a Union here, replace with Tuple if you 
    Type.Object({                   // expect exactly two elements.
      type: Type.Literal('B1'),
      x: Type.String()
    }),
    Type.Object({ 
      type: Type.Literal('B2'),
      y: Type.Number()
    })

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Ghirigoro
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