[英]type defenition problem. can't get rid of type any
我需要从模板对象加载一些小部件(以后可能是 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
类型转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.