【问题标题】:type defenition problem. can't get rid of type any类型定义问题。无法摆脱任何类型
【发布时间】:2021-03-19 12:53:03
【问题描述】:

我需要从模板对象加载一些小部件(以后可能是 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 之类的参数传递给构造函数,并强制将其强制转换为 any。无法弄清楚如何正确地做到这一点。 ts playground link

【问题讨论】:

    标签: javascript typescript types casting


    【解决方案1】:

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

    【讨论】:

    • 是的,name 匹配一组特定的道具。
    • 如此简单的解决方案。谢谢!你是最棒的!
    猜你喜欢
    • 2023-04-03
    • 2016-08-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 2017-12-07
    相关资源
    最近更新 更多