Skip to content

Adding closure support for circular types #39

@ahdinosaur

Description

@ahdinosaur

hi 😺

i was getting amongst computed-types for a side project i'm playing with, and then i realized the types i want to validate are circular, e.g. a tree data structure. i was wondering if it might be possible to use computed-types with circular types.

i made a simplified example to show what i mean, and what i have working so far: https://repl.it/talk/share/circular-computed-types/43342

// mod.ts

import Schema, { Type, string, array } from 'https://denoporter.sirjosh.workers.dev/v1/deno.land/x/computed_types/src/index.ts'

// lazy due to circular evaluation
let _NodeSchema: any = null
export const NodeSchema: any = function (...args: Array<any>): any {
  if (_NodeSchema == null) throw new Error('programmer error')
  return _NodeSchema(...args)
}

export type Node = Branch | Leaf

export const BranchSchema = Schema({
  name: string.trim().normalize(),
  nodes: array.of(NodeSchema),
})

export type Branch = Type<typeof BranchSchema>

export const LeafSchema = Schema({
  name: string.trim().normalize()
})

export type Leaf = Type<typeof LeafSchema>

_NodeSchema = Schema.either(BranchSchema, LeafSchema)
import { NodeSchema } from './mod.ts'

const node = NodeSchema({
  name: 'a',
  nodes: [
    {
      name: 'b'
    },
    {
      name: 'c',
      nodes: [
        {
          name: 'd',
          nodes: [
            {
              name: 'e'
            }
          ]
        },
        {
          name: 'f'
        }
      ]
    }
  ]
})

console.log(JSON.stringify(node, null, 2))

i'm able to get the runtime to work with a silly hack, but i'm stuck on getting the types to work.

was wondering, is this something that might be possible to do?

cheers! 💜

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthelp wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions