2016-12-05 115 views
2

我想要一个变量来存储一个类实例数组,但我想指定数据类型作为从“基”类继承的任何东西。这更好地通过示例演示:TypeScript变量,它包含一个扩展基类的类实例

class Mom { } //Base class 
class Son extends Mom { } 
class Daughter extends Mom { } 

//What is the syntax for this? 
let example : <T extends Mom>T[] = [ ]; //This array should store anyting that extends 'Mom' 

//The this would be possible 
example.push(new Mom()); 
example.push(new Son()); 
example.push(new Daughter()); 

在此先感谢。

+0

如何:'我们例子= []作为妈妈[];'? –

回答

4

尝试这种方式

let example : Array<Mom> = [ ]; 

here

+0

这是否包括延伸妈妈的东西?因为它不是很详细。 –

+0

@CameronBell是的一切是妈妈 –

1

你可以做这样的事情

type Shape = Mom | Son | Daughter; 
let example:Array<Shape> = new Array<Shape>(); 
+0

但是,然后我将不得不手动添加我想要的每个类。无论如何要自动做到这一点? –

+0

在你的情况只是**数组 **是好的,将工作。 – kimy82