我很难让 TypeScript 编译器不给我带来悲伤。我有一个 Controller ,它有一个类数组,不是类的实例,而是类本身。所有这些都将从同一个基础 UnitView
扩展。由于某种原因,如果我的 TitleView
不接受泛型,我会收到错误,但如果接受,我不会收到错误。
我不明白为什么 TitleView
需要接受泛型,因为它将模型类型显式传递给 UnitView
。任何人都可以解释或看到我做错了什么吗?
代码:
class Model { }
class View<TModel extends Model> {
private model: TModel;
}
class UnitView<TModel extends Model> extends View<TModel> { }
class TitleView extends UnitView<Model> { }
class Controller {
private ViewClass: typeof UnitView;
private ViewClasses: typeof UnitView[] = [
TitleView
]
}
和here如果您想在那里进行测试,可以直接链接到 TypeScript Playground
最佳答案
该错误与数组无关。这是您的错误的最小重现:
class View<TModel> {
model: TModel;
}
class UnitView<TModel> extends View<TModel> { }
class TitleView extends UnitView<{}> { }
const example1: typeof UnitView = TitleView; // ERROR
TileView
不能分配给typeof UnitView
。关键原因是 T
的类型(泛型)与 {}
不兼容。
这类似于下面所示的进一步简化示例:
class Foo<T> {
model: T
}
class Bar{
model: {}
}
const example2: typeof Foo = Bar; // ERROR
TLDR
泛型 T
和实例(甚至 {}
)不兼容赋值。这是设计使然。
更多
保持兼容的唯一方法是保留通用
,例如
class Foo<T> {
model: T
}
class Bar<T>{
model: T
}
const example3: typeof Foo = Bar; // Okay
关于javascript - 泛型类的 TypeScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46333184/