首页 > 解决方案 > 类型定义问题。无法摆脱任何类型

问题描述

我需要从模板对象加载一些小部件(以后可能是 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游乐场链接

标签: javascripttypescripttypescasting

解决方案


首先,鉴于您应该知道 的类型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类型转换。


推荐阅读