问题:
我试图从一个高阶类方法返回一个类声明,该类方法从一个类映射中扩展一个类,该类映射的{"SOME_CLASS" : SomeClass}
键是高阶类方法的参数。但是 Typescript 抛出了这个错误......
注意:我没有使用任何外部库。
错误:
不能将“new”与类型缺少调用或构造签名的表达式一起使用。
尝试:
我试图将 Class Type 转换为“Newable”,但是我失去了对正在扩展的类的类型绑定。
片段
/// 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
}
请原谅任何格式错误,这可能是我关于堆栈溢出的第二篇文章。干杯!
来自评论的更新类返回类扩展另一个类的示例
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;
}
}
}
}