Typescript typebox: static initialization

633 views Asked by At

I have two classes where I want to define a static Schema property using typebox. I also need to define a dependency between the two classes: first class schema must have an array of type of the second class schema:

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

class ClassA {
    static Schema = Type.Object({
        id: Type.String(),
        data: Type.Array(ClassB.Schema) // ERROR: <-- Property 'Schema' is used before its initialization.
    })
    
    constructor(id: string, data: ClassB[]) {
        this.id = id;
        this.data = data;
    }
    
    public id: string;
    public data: ClassB[];
}

class ClassB {
    static Schema = Type.Object({
        id: Type.String(),
    })

    constructor(id: string) {
        this.id = id;
    }
    
    public id: string;
}

Problem is I can't pass ClassB.Schema as argument for Type.Array(), I got the error: Property 'Schema' is used before its initialization. I thought that since both are static properties, they are evaluated at the same time but it doesn't seem the case. Any idea how to workaround this?

1

There are 1 answers

2
revy On

Well, it seems it is enough to invert the order of class declarations...

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

class ClassB {
    static Schema = Type.Object({
        id: Type.String(),
    })

    constructor(id: string) {
        this.id = id;
    }

    public id: string;
}

class ClassA {
    static Schema = Type.Object({
        id: Type.String(),
        data: Type.Array(ClassB.Schema)
    })

    constructor(id: string, data: ClassB[]) {
        this.id = id;
        this.data = data;
    }

    public id: string;
    public data: ClassB[];
}