Passing schemas to functions that are piped

I have a bunch of incoming events that I need to parse and validate. They all have a common structure. I'm wanting to build a more generic system where you can pass what events to "subscribe" to.

This was working great until I had an event that had a .pipe().

Any ideas how I can get around this?

const BaseEvent = type({
    type: "string",
    timestamp: "number",
});

const SomeEvent = BaseEvent.and({
    type: "'some_event'",
    data: {
        foo: "string",
    },
});

const SomePipedEvent = BaseEvent.and({
    type: "'some_piped_event'",
    data: {
        bar: "string",
    },
}).pipe((o) => {
    return {
        ...o,
        data: {
            ...o.data,
            someExtraField: 5,
        },
    };
});

class EventListener<T extends typeof BaseEvent> {
    constructor(events: T[]) {
    }

    public on(event: T['infer']['type'], callback: (event: T['infer']) => void) {
    }
}

/* All the code below has type errors */
const listener = new EventListener([SomeEvent, SomePipedEvent]);

listener.on("some_event", (event) => {
    event.data.foo
});

listener.on("some_piped_event", (event) => {
    event.data.someExtraField
});
Was this page helpful?