5

I want to have a variable to stores a class instance array, but I want to specify the data type as anything that inherits from a 'base' class. This better demonstrated by example:

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());

Thanks in advance.

1
  • How about: let example = [] as Mom[];? Commented Dec 5, 2016 at 11:50

2 Answers 2

3

Try this way

let example : Array<Mom> = [ ];

See here

Sign up to request clarification or add additional context in comments.

2 Comments

Does this include thing that extend mom? Because it is not very verbose.
@CameronBell yes everything that is Mom
2

You can do things like

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

3 Comments

But then I would have to manually add every class that I want. Is there anyway to do this automatically?
In your case just Array<Mom> is fine and Will work.
you can also do this: let example = Shape[] = { .. }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.