抽象类的具体子类的 typescript 类型

标签 typescript typescript1.8

我正在尝试在 Typescript 中解决这个特定案例:

Typescript Playground link

abstract class foo {
    abstract bar();
}

class Foo1 extends foo {
    bar() {
        alert(1);
    }

    y: number = 3;
}

class Foo2 extends foo {
    bar() {
        alert(2);
    }
}

let myFooClasses: Array<typeof foo> = [];
myFooClasses.push(Foo1);
myFooClasses.push(Foo2);

myFooClasses.forEach((item) => {
    let a = new item();
    a.bar();
})

具体来说,问题是 myFooClasses 在技术上可能包含抽象的 foo 并且 Typescript 对此发出警告。但我真的想将 myFooClasses 的类型限制为继承自 foo 的具体类。有没有办法在 Typescript 中指定它?

最佳答案

你的数组类型应该是:

let myFooClasses: Array<{ new (): foo }> = [];

然后是:

myFooClasses.push(foo);

产生这个错误:

Argument of type 'typeof foo' is not assignable to parameter of type '{ new (): foo }'. Can not assign an abstract constructor type to a non-abstract constructor type.

您还可以:

type FooConstructor = { new (): foo };
let myFooClasses: FooConstructor[] = [];

关于抽象类的具体子类的 typescript 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37618525/

相关文章:

reactjs - PayloadAction 的 typescript 类型

javascript - 在 AngularFire2 中获取用户 ID 的最安全方法

typescript - 如何在 typescript 类型中定义默认值

inheritance - TypeScript:静态属性和继承

javascript - 在 Angular 2 中的 Observable 中获取数据后的队列/回调函数

javascript - Angular Reactive 表单禁用 p-dropdown 中的特定选项

javascript - 子组件之间的通信 - 触发和更改

node.js - 如何在 Angular Web Worker 中导入 Node 模块?

类型定义文件中的 Typescript 编译错误

typescript - TypeScript 项目的目录结构