【发布时间】:2018-05-08 10:32:30
【问题描述】:
谁能解释一下,为什么这段代码不起作用:
class Fooable {
foo: string;
}
class Barable extends Fooable {
bar: boolean;
}
function simplifiedExample<T extends Fooable>(): Array<T> {
let list = new Array<T>();
list.push(new Barable());
return list;
}
Barable 正在扩展 Fooable。当 T 必须是 Fooable 时,为什么我不能将 Barable 添加到数组中? 这里代码在playground
编辑:
问题是,simplifiedExample() 是基类的覆盖,基类只是一个定义。因为是一个混合项目 JS/TS。
我找到了一个带有演员表的解决方案,但对我来说这似乎不是一个合适的解决方案:
class BarableService extends FooableService {
simplifiedExample<T extends Fooable>(): Array<T> {
let list = new Array<Fooable>();
list.push(new Barable());
return list as Array<T>;
}
}
【问题讨论】:
标签: typescript generics inheritance