我试图从更高阶的类方法返回一个类声明,该方法从类映射{"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;
}
}
}
}
答案 0 :(得分:0)
这在TypeScript中不起作用。
TypeScript中的类型系统仅在编译时存在。
编译代码时,它是纯JavaScript。
您无法定义新类和/或从仅在运行时知道的另一个类扩展它。