Recommendation for nested recursive object value #611
Replies: 1 comment 1 reply
-
@rijkvanzanten Heya, TypeBox only supports recursive types that are "not" infinitely expansive. The issue here that the const Key = Type.String()
const Rules = Type.Recursive(This => Type.Record(Key, This))
type Rules = Static<typeof Rules> // Type instantiation is excessively deep and possibly infinite.
// Reason: [key: string] is infinitely expansive (potentially infinite properties) However, if you constrain the keys to a finite set, this type becomes possible. const Key = Type.Union([
Type.Literal('A'),
Type.Literal('B'),
Type.Literal('C'),
])
const Rules = Type.Recursive(This => Type.Record(Key, This))
type Rules = Static<typeof Rules> // fine This rule pops up in various places, for example, recursive arrays. const Rules = Type.Recursive(This => Type.Array(This))
type Rules = Static<typeof Rules> // Type instantiation is excessively deep and possibly infinite.
// Reasons: This types generic argument is infinitely described by itself (Array<infinity>)
// This type evaluates [][][][][][][].... (into infinity) Generally you want to avoid creating infinitely expansive types when using TypeBox as it's not possible to infer without infinitely expanding generic arguments, but if you need them, you can express them via import { Type, Static } from '@sinclair/typebox'
type Value = string | number
interface Rules {
foo: Value
bar: {
baz: Value
}
}
interface CustomRules {
[key: string]: Value | CustomRules
}
const Schema = Type.Unsafe<Rules & CustomRules>({ /* ... Define JSON Schema here */ })
type Schema = Static<typeof Schema> Documentation on Type.Unsafe can be found https://github.com/sinclairzx81/typebox#types-unsafe. |
Beta Was this translation helpful? Give feedback.
-
Hi there!
I'm trying to achieve an object schema where there's a handful of known (required) properties of a given value, but then allow any additional properties to be added that adhere to the same value. In TypeScript, I would define that as:
I've unsuccessfully tried achieving this through TypeBox as:
but that unfortunately results in a
Type instantiation is excessively deep and possibly infinite.
error from TypeScript.Are the types I'm trying to achieve possible through TypeBox? And if so, do you have any recommendations on how to achieve this goal? Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions