openlang

TypeScript array accepting objects derived from one shared parent class

I'd like a variable holding an array of class instances, with its element type allowing anything derived from a 'base' class. This example of the class-instance array explains what I mean:

class Parent { } //Common parent
class FirstChild extends Parent { }
class SecondChild extends Parent { }

//How should this declaration look?
let instances: <U extends Parent>U[] = []; //Allow all descedants of 'Parent' here

//Then these calls would work
instances.push(new Parent());
instances.push(new FirstChild());
instances.push(new SecondChild());

Thank you beforehand.

The conversation continues 2

Follow the reasoning
  1. Permalink

    One option for your class-instance array is

    type Family = Parent | FirstChild | SecondChild;
    let instances: Array<Family> = new Array<Family>();

Other sides of the same question

  1. TypeScript Map initialization with string array entries

    I'm creating a Map whose entries each hold an array of strings. How can I declare its type and initialize it together in one…

    Replies 2Latest activity typescript
  2. Typescript Callable Contract

    Why does Typescript accept my function definition even though it differs from the interface signature, yet report a problem w…

    Replies 2Latest activity typescript
  3. Solidity conversion failure from address into uint256

    I made an array containing structs, then attempted to retrieve each account's values from that array. But passing an address…

    Replies 3Latest activity solidity