我有一个基本的泛型类:
abstract class BaseClass<T> {
abstract itemArray: Array<T>;
static getName(): string {
throw new Error(`BaseClass - 'getName' was not overridden!`);
}
internalLogic() {}
}
和继承者:
type Item1 = {
name: string
}
class Child1 extends BaseClass<Item1> {
itemArray: Array<Item1> = [];
static getName(): string {
return "Child1";
}
}
type Item2 = {
name: number
}
class Child2 extends BaseClass<Item2> {
itemArray: Array<Item2> = [];
static getName(): string {
return "Child2";
}
}
现在我想定义一个以继承者为值的对象:
type IChildrenObj = {
[key: string]: InstanceType<typeof BaseClass>;
};
/*
The following error is received: Type 'typeof BaseClass' does not satisfy the constraint 'new (...args: any) => any'.
Cannot assign an abstract constructor type to a non-abstract constructor type. ts(2344)
*/
const Children: IChildrenObj = {
C1: Child1,
C2: Child2,
}
最后,我希望能够使用子项的静态方法,并且还能够创建它们的实例:
const child: typeof BaseClass = Children.C1;
/*
received the following error: Property 'prototype' is missing in type '{ getName: () => string; }' but required in type 'typeof BaseClass'. ts(2741)
*/
console.log(child.getName());
const childInstance: BaseClass = new child();
/*
The following 2 errors are received:
(1) Generic type 'BaseClass<T>' requires 1 type argument(s). ts(2314)
(2) Cannot create an instance of an abstract class. ts(2511)
Generic type 'BaseClass<T>' requires 1 type argument(s). ts(2314)
*/
答案 0 :(得分:2)
首先是类型
type IChildrenObj = {
[key: string]: InstanceType<typeof BaseClass>; // instances?
};
不适合描述您的 Children
对象。 Children
存储类构造函数而InstanceType<typeof BaseClass>
,即使它适用于抽象类(正如您所指出的,它不是),也会谈论类实例。写起来会更接近
type IChildrenObj = {
[key: string]: typeof BaseClass; // more like constructors
};
但这也不是 Children
存储的内容:
const Children: IChildrenObj = {
C1: Child1, // error!
// Type 'typeof Child1' is not assignable to type 'typeof BaseClass'.
// Construct signature return types 'Child1' and 'BaseClass<T>' are incompatible.
C2: Child2, // error!
// Type 'typeof Child2' is not assignable to type 'typeof BaseClass'.
// Construct signature return types 'Child2' and 'BaseClass<T>' are incompatible.
}
类型typeof BaseClass
有一个抽象构造签名,看起来像new <T>() => BaseClass<T>
;调用者(或更有用的是,扩展 BaseClass
的子类)可以为 T
选择他们想要的任何东西,而 BaseClass
必须能够处理它。但是 typeof Child1
和 typeof Child2
类型不能为 BaseClass<T>
的调用者或扩展者 T
想要的任何 new Child1()
生成 class Grandchild2 extends Child2
; Child1
只能构造一个 BaseClass<Item1>
,而 Child2
只能构造一个 BaseClass<Item2>
。
所以目前 IChildrenObj
表示它拥有构造函数,每个构造函数都可以为 每种 可能的类型 BaseClass<T>
生成一个 T
。您真正想要的是 IChildrenObj
说它拥有构造函数,每个构造函数都可以为 some 可能的类型 BaseClass<T>
生成一个 T
。 “every”和“some”之间的区别与类型参数 T
与 quantified 之间的区别有关; TypeScript(以及大多数其他具有泛型的语言)仅直接支持“every”或通用量化。不幸的是,没有对“某些”或存在量化的直接支持。有关开放功能请求,请参阅 microsoft/TypeScript#14446。
有一些方法可以在 TypeScript 中准确地编码存在类型,但是除非您真的关心类型安全,否则这些方法使用起来可能有点烦人。 (但如果需要,我可以详细说明)
相反,我在这里的建议可能是重视生产力而不是完全类型安全,只需使用 the intentionally loose any
type 来表示您不关心的 T
。
所以,这里有一种定义 IChildrenObj
的方法:
type SubclassOfBaseClass =
(new () => BaseClass<any>) & // a concrete constructor of BaseClass<any>
{ [K in keyof typeof BaseClass]: typeof BaseClass[K] } // the statics without the abstract ctor
/* type SubclassOfBaseClass = (new () => BaseClass<any>) & {
prototype: BaseClass<any>;
getName: () => string;
} */
type IChildrenObj = {
[key: string]: SubclassofBaseClass
}
类型 SubclassOfBaseClass
是 intersection 的:产生 BaseClass<any>
实例的具体 construct signature;和一个 mapped type,它从 typeof BaseClass
中获取所有静态成员,而不会同时获取有问题的抽象构造签名。
让我们确保它有效:
const Children: IChildrenObj = {
C1: Child1,
C2: Child2,
} // okay
const nums = Object.values(Children)
.map(ctor => new ctor().itemArray.length); // number[]
console.log(nums); // [0, 0]
const names = Object.values(Children)
.map(ctor => ctor.getName()) // string[]
console.log(names); // ["Child1", "Child2"]
看起来不错。
这里的警告是,虽然 IChildrenObj
可以工作,但它的类型太模糊,无法跟踪您可能关心的事情,例如 Children
的特定键/值对,以及尤其是 index signatures 和 any
中的 BaseClass<any>
的奇怪的“任何事情都会发生”行为:
// index signatures pretend every key exists:
try {
new Children.C4Explosives() // compiles okay, but
} catch (err) {
console.log(err); // ? RUNTIME: Children.C4Explosives is not a constructor
}
// BaseClass<any> means you no longer care about what T is:
new Children.C1().itemArray.push("Hey, this isn't an Item1") // no error anywhere
因此,在这种情况下,我的建议是仅确保 Children
可分配给 IChildrenObj
,而无需对其进行实际注释。例如,您可以使用辅助函数:
const asChildrenObj = <T extends IChildrenObj>(t: T) => t;
const Children = asChildrenObj({
C1: Child1,
C2: Child2,
}); // okay
现在 Children
仍然可以在您需要 IChildrenObj
的任何地方使用,但它仍然记住所有特定的键/值映射,因此在您做坏事时会发出错误:
new Children.C4Explosives() // compiler error!
//Property 'C4Explosives' does not exist on type '{ C1: typeof Child1; C2: typeof Child2; }'
new Children.C1().itemArray.push("Hey, this isn't an Item1") // compiler error!
// Argument of type 'string' is not assignable to parameter of type 'Item1'
如果需要,您仍然可以使用 IChildrenObj
:
const anotherCopy: IChildrenObj = {};
(Object.keys(Children) as Array<keyof typeof Children>)
.forEach(k => anotherCopy[k] = Children[k]);