javascript - 泛型类的 TypeScript 数组

标签 javascript typescript generics

我很难让 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/

相关文章:

javascript - jQuery .show 无法在 .each 中工作

javascript - 分页器表在 Jquery ajax 查询后不分页

angular - 为什么从 es2015 到 esm2015 编译 Angular 依赖会删除环境中的 html 标签?

reactjs - eslint:无法解析模块 'src/interfaces' 的路径

c# - 通用抽象方法

c# - 如何在 C# 中的基类型列表中使用 Foreach

c# - 我可以在这里用什么来模拟? (通配符)C# 中的泛型?

javascript - 使用 globalCompositeOperation 创建渐变 mask

javascript - Highcharts:如何使用 setData 添加系列

angular - 无法在 getRequiredModulePath 处读取 NodeObject.getText 处未定义的属性 'text'