HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptMajor

Class constructor type in typescript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typeclassconstructortypescript

Problem

How can I declare a class type, so that I ensure the object is a constructor of a general class?

In the following example, I want to know which type should I give to AnimalClass so that it could either be Penguin or Lion:

class Animal {
    constructor() {
        console.log("Animal");
    }
}

class Penguin extends Animal {
    constructor() {
        super();
        console.log("Penguin");
    }
}

class Lion extends Animal {
    constructor() {
        super();
        console.log("Lion");
    }
}

class Zoo {
    AnimalClass: class // AnimalClass could be 'Lion' or 'Penguin'

    constructor(AnimalClass: class) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}


Of course, the class type does not work, and it would be too general anyway.

Solution

I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:

class Zoo {
constructor(public readonly AnimalClass: new () => T) {
}
}


This way variables penguin and lion infer concrete type Penguin or Lion even in the TypeScript intellisense.

const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); //
penguin is of Penguin type.

const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); //
lion is Lion type.

Context

Stack Overflow Q#39614311, score: 87

Revisions (0)

No revisions yet.