Class constructor type in typescript? Class constructor type in typescript? typescript typescript

Class constructor type in typescript?


Solution from typescript interfaces reference:

interface ClockConstructor {    new (hour: number, minute: number): ClockInterface;}interface ClockInterface {    tick();}function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {    return new ctor(hour, minute);}class DigitalClock implements ClockInterface {    constructor(h: number, m: number) { }    tick() {        console.log("beep beep");    }}class AnalogClock implements ClockInterface {    constructor(h: number, m: number) { }    tick() {        console.log("tick tock");    }}let digital = createClock(DigitalClock, 12, 17);let analog = createClock(AnalogClock, 7, 32);

So the previous example becomes:

interface AnimalConstructor {    new (): Animal;}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: AnimalConstructor // AnimalClass can be 'Lion' or 'Penguin'    constructor(AnimalClass: AnimalConstructor) {        this.AnimalClass = AnimalClass        let Hector = new AnimalClass();    }}


Like that:

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

Or just:

class Zoo {    constructor(public AnimalClass: typeof Animal ) {        let Hector = new AnimalClass();    }}

typeof Class is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.

Here's the relevant part of TypeScript docs. Search for the typeof. As a part of a TypeScript type annotation, it means "give me the type of the symbol called Animal" which is the type of the class constructor function in our case.


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<T extends Animal> {    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.