I am trying to load some widgets from a template object (possibly JSON in the future). Here's an example:
type RectangleTemplate = {
name: 'Rectangle';
props: {
width: number;
height: number;
}
};
type ButtonTemplate = {
name: 'Button';
props: {
text: string;
}
};
type Template = ButtonTemplate | RectangleTemplate;
class Button {
constructor(template: ButtonTemplate) {
console.log(template.name);
}
}
class Rectangle {
constructor(template: RectangleTemplate) {
console.log(template.name);
}
}
const widgets = { Button, Rectangle }
const createWidget = (template: Template): void => {
const ctor = widgets[template.name as keyof typeof widgets];
const node = new ctor(template as any);
};
const template: Template = {
name: 'Button',
props: {
text: 'button'
}
}
const widget = createWidget(template);
The issue lies in this line:
const node = new ctor(template as any);
. I am unable to pass the argument as template: Template
to the constructor and am forced to cast it as any. I can't figure out the correct way to do this.
ts playground link