Skip to content

Instantly share code, notes, and snippets.

@yairhaimo
Last active February 3, 2023 18:59
Show Gist options
  • Save yairhaimo/12f2f0857811a6d376f7d0678164354a to your computer and use it in GitHub Desktop.
Save yairhaimo/12f2f0857811a6d376f7d0678164354a to your computer and use it in GitHub Desktop.
Typed builder

To whom it may concern, thanks in advance!

It's a bit of a read but there's only one question :)


Im creating a builder class that can create nodes:

builder.createNode1().createNode2().createNode3().createNode4().getNodes();

Each node has an input and output object. I want to be able to reference the output of previous nodes in the input of another node:

builder.createNode1().createNode2(builder => ({
  node2InputProperty1: builder.values.prev /* special keyword */.node1OutputProperty1, // <-- this should be typed
  node2InputProperty2: builder.values.0/* node Index */.node1OutputProperty2, // <-- can use node index or the "prev" keyword
  })).getNodes();

The builder class is a generic class which receives the previous node's output as a type. I'm having a bit of a problem getting the types right for the values property.

class Builder<T> {
  constructor(private nodes: Node[]) {}

  createNode1(/* ... */) {
    const node = new Node1(/* ... */); // { id, input, output }
    this.nodes.push(node);
    return new Builder<Node1Output>(this.nodes);
  }

  createNode2(/* ... */) {
    const node = new Node2(/* ... */); // { id, input, output }
    this.nodes.push(node);
    return new Builder<Node2Output>(this.nodes);
  }

  getNodes() {
    return this.nodes;
  }

  values = { // <-- this should be dynamic and typed
    0: {
      text: 'placeholder value' // <-- it should type "text" for index "0"
    },
    1: {
      url: 'placeholder value' // <-- type "url" for index "1"
    },
    prev: {
      url: 'placeholder value' // <-- type "url" for the previous node (according to T)
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment