简体   繁体   中英

TypeScript variable that hold a class instance that extends a base class

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.

Try this way

let example : Array<Mom> = [ ];

See here

You can do things like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM