In my project, I am in the process of developing a custom DOM with unique nodes. I want to create a method similar to createElement
which will take the nodeName as an argument and return an instance of the corresponding Node.
import { Node } from "./tree";
export class DOM
{
private defs: Record<string, new () => Node>;
constructor(nodeDefs: Record<string, new () => Node>)
{
for (const [nodeName, NodePrototype] of Object.entries(nodeDefs))
this.defs[nodeName] = NodePrototype;
}
create(nodeName: keyof typeof this.defs)
{
const newNode = new this.defs[nodeName]();
newNode.name = nodeName;
return newNode;
}
}
The current code functions properly, but I find that it lacks hints about available node names and the return type is always just Node
, rather than the specific type of node being created.
How can I modify the above code to ensure accurate and helpful hints during development?
const dom = new DOM({
paragraph: Paragraph,
text: Text
});
const myP = dom.create('paragraph'); // Accurate type hints now provided!