import { IParser, OnParse } from "./interfaces"; import { Parser } from "./parser"; /** * This is needed when the typescript has a recursive, mutual types * type Things = string | [OtherThings] * type OtherThings = {type: 'other', value:Things } */ export class DeferredParser implements IParser { private parser?: Parser; static create(): DeferredParser { return new DeferredParser(); } private constructor( readonly description = { name: "Deferred", children: [], extras: [], } as const, ) {} setParser(parser: IParser) { this.parser = new Parser(parser); return this; } parse(a: unknown, onParse: OnParse): C | D { if (!this.parser) { return onParse.invalid({ value: "Not Set Up", keys: [], parser: this, }); } return this.parser.parse(a, onParse); } } /** * Must pass the shape that we expect since typescript as of this point * can't infer with recursive like structures like this. * @returns [Parser, setParser] Use the setParser to set the parser later */ export function deferred() { const deferred = DeferredParser.create(); function setParser(parser: IParser) { deferred.setParser(parser); } return [new Parser(deferred), setParser] as const; }