使用打字稿管理正确的重载

时间:2019-04-24 08:23:26

标签: typescript

这是我在课堂上的代码:

  public dangerouslyAttachCustomTag(
    tagName: string,
    content: string,
    attributes?: AttributeObject
  ): VastElement<this>;
  public dangerouslyAttachCustomTag(
    tagName: string,
    attributes?: AttributeObject
  ): VastElement<this>;
  public dangerouslyAttachCustomTag(
    tagName: string,
    contentOrAttributes: AttributeObject | string,
    attributesIfContent?: AttributeObject
  ): VastElement<this> {
    const newElem = new VastElement(
      tagName,
      this,
      { attrs: "all" },
      contentOrAttributes as any, // how to remove this any ?
      attributesIfContent
    );

    this.childs.push(newElem);
    return newElem;
  }

我在这里担心的是,我可以通过以下三种方式调用我的课程:

v.dangerouslyAddCustomTag("test1")
v.dangerouslyAddCustomTag("test2", { id: "22" })
v.dangerouslyAddCustomTag("test3", "content3", { id: "33" });

但是由于我的构造函数具有此签名:

  constructor(
    name: string,
    parent: VastElementParent,
    baseInfos: VastElementInfos,
    content: string,
    attrs?: AttributeObject
  );
  constructor(
    name: string,
    parent: VastElementParent,
    baseInfos: VastElementInfos,
    attrs?: AttributeObject
  );
  constructor();
  constructor(
    name: string = "root",
    parent: VastElementParent = null,
    baseInfos: VastElementInfos = { attrs: [] },
    contentOrAttributes?: AttributeObject | string,
    attributesIfContent?: AttributeObject
  ) 

我无法删除“ dangerouslyAttachCustomTag”中的“任何”。

超载应如何允许呢?

0 个答案:

没有答案