javascript - 类型定义问题。无法摆脱任何类型
问题描述
我需要从模板对象加载一些小部件(以后可能是 json)。这是一个例子:
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);
问题出在这一行:const node = new ctor(template as any);
. 我不能像template: Template
构造函数那样传递参数,并强制将其强制转换为任何参数。无法弄清楚如何正确地做到这一点。
ts游乐场链接
解决方案
首先,鉴于您应该知道 的类型shape
,您可以将它们添加到ShapeNames
类型中。
type ShapeNames = 'Rectangle' | 'Button'; // append the rest of the possible shapes
其次,为每个形状创建一个 TemplateProps 类型,并将它们添加到父类型ShapeTemplateProps
中。
type RectangleTemplateProps = {
width: number;
height: number;
}
type ButtonTemplateProps = {
text: string;
}
// Append additional templateProps type below
type ShapeTemplateProps = RectangleTemplateProps | ButtonTemplateProps;
接下来,将ShapeTemplateProps
类型分配给props
.
type RectangleTemplate = {
name: ShapeNames;
props: ShapeTemplateProps;
};
type ButtonTemplate = {
name: ShapeNames;
props: ShapeTemplateProps;
};
最后,删除as any
类型转换。
推荐阅读
- java - Apache Spark 的大量列名称中包含模式的错误记录
- javascript - 如何在 highchart 中使用下面的 fillOpacity 到 PlotLine?
- python - 如何动态拟合作物植物的 sigmoid 生长曲线?
- r - R中的循环命令
- string - 如何转换 Vec
到 &[&str]? - javascript - 我们如何在本地运行 diagrams.net 源代码
- flutter - 如何在颤动中做出这样的下拉菜单?
- sql - 从 SQL 中的基表创建具有上次修改日期时间的时间戳的视图
- java - 如何测试 Spring Boot JdbcTest 切片
- android - 让用户从可绘制文件夹中选择图像