Simulate inheritance #625
-
Is there a way to simulate inheritance using Typebox? Say I have a type that looks like this: type A = {
id:string,
elements: [...{type:string}[]]
} And I need to create other types that extend it: type B = {
id:"B",
elements: [{type:"B1", x:string}, {type:"B2", y:number}]
} How would I create a schema for |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
@Ghirigoro Hi, You can use either Type.Intersect() or Type.Composite() to extend a base type. The example below extends using Composite. 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()
})
]))
})])
type Base = Static<typeof Base>
type Derived = Static<typeof Derived> Above, the Derived type actually narrows the Hope this helps |
Beta Was this translation helpful? Give feedback.
@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