LongInt
LongInt

Reputation: 1769

Proper type of object of constructors

I have the following object:

export const PageConstructors: {[index: string]: any} = {
    [PageName.MAIN] : MainPage,
    [PageName.SCOREBOARD] : ScoreboardPage,
};

MainPage and ScoreboardPage are both children of Page. I want to replace the any with the correct type. However I am stumped in finding the right typescript syntax. I've tried various combinations of new<T extends Page>() => T without luck. Is this possible?

Upvotes: 0

Views: 23

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

The constructor itself is not generic. Your constructor signature can return the base class instead.

class Parent {
    constructor() {

    }
}
class Child extends Parent {
    constructor() {
        super();        
    }
}


const constructors: { [index: string]: new () => Parent } = {
    test: Child,
}

If the constructor can take arguments you can take a rest of any or unknown

const constructors: { [index: string]: new (...a:unknown[]) => Parent } = {
    test: Child,
}

Upvotes: 1

Related Questions