无法从类字典扩展类

问题描述 投票:2回答:1

ISSUE:

我试图从更高阶类方法返回一个类声明,该方法从类映射扩展一个类{"SOME_CLASS" : SomeClass},其中key是高阶类方法的参数。然而,Typescript却抛出了这个错误...... 注意:我没有使用任何外部库。

ERROR:

不能对类型缺少调用或构造签名的表达式使用“new”。

ATTEMPTS:

我试图将类类型转换为“可更新”但是我丢失了对正在扩展的类的类型绑定。

SNIPPET

/// Contrived Example
interface BaseConfig {
  options: {
    profileHref: string
  }
}
abstract class Base { /*< BaseClass Implementations >*/
}
/// Example Class 1
class ProfileIcon extends Base {
  constructor(config: {
    options: {
      profileHref: string
    }
  }) {
    super(config);
  }
}
/// Example Class 2
class ScriptBlock extends Base {
  constructor(config: {
    options: {
      src: string
    }
  }) {
    super(config);
  }
}
}

class Manager {
  protected STORE: RootStore;
  constructor() {}
  public dispatchNewElement(elementType: keyof typeof ELEMENT_MANIFEST) {
    const storeShard = this.STORE.shard();
    const elementClass = ELEMENT_MANIFEST[elementType];


    /*
    //// ERROR: type 'typeof ProfileIcon | typeof ScriptBlock' is not a constructor function type.
    /// NOTE: 
    >> const T = new elementClass(...args)
    >> throws - Cannot use 'new' with an expression whose type lacks a call or construct signature.
    ////
    ////
    */

    return class extends /*err*/ elementClass /*endErr*/ {
      protected STORE_SHARD: typeof RootStore;
      constructor(elementConfig: { < unique fields to class implementation >
      }) {
        super(elementConfig);
        this.STORE_SHARD = storeShard;
      }
    }
  }

  /// Element Class Dictionary
  const ELEMENT_MANIFEST = {
    "PROFILE_ICON": ProfileIcon,
    "SCRIPT_BLOCK": ScriptBlock
  }

请原谅任何错误格式化,这可能是我关于堆栈溢出的第二篇文章。干杯!

UPDATE from Comments

类返回类扩展另一个类的示例

class Master {
    public STATE: any;
    constructor() {
        this.STATE = { name: "foo" };
    }
    public dispatchNewClass(classType: string) {
        const myRefImage = Img;
        ////
        /* Works as a refVariable however..
        if i declare like...
            const myRefImage: Icon | Img
        I will get  
        >> Type 'typeof Img' is not assignable to type 'Icon | Img'.  
        >> Type 'typeof Img' is not assignable to type 'Img'.  
        >>Property 'TagName' is missing in type 'typeof Img'.
        */
        ///
        const asObject {}
        const ROOT = this.STATE;
        return class Slave extends myRefImage {
            protected ROOT: typeof ROOT;
            constructor(tagName: string) {
                super(tagName as "img")
                this.ROOT = ROOT;
            }
        }
    }
}
typescript types casting extending-classes
1个回答
0
投票

这在TypeScript中不起作用。

TypeScript中的类型系统仅在编译时存在。

编译代码时,它是纯JavaScript。

您无法定义新类和/或从仅在运行时知道的另一个类扩展它。

© www.soinside.com 2019 - 2024. All rights reserved.