Michael Tsang
Michael Tsang

Reputation: 781

How can I use a dynamic class in a TypeScript type declaration?

I'm doing some "inner class" stuff in TypeScript by assigning class into variables. Here's an example code:

export default class Kmb {
    public readonly Stop; // inner class
    public readonly StopRoute; // inner class
    public constructor() {
        const kmb = this;
        this.Stop = class Stop {
            // some methods referencing kmb
        };
        this.StopRoute = class StopRoute {
            public readonly stop;
            public constructor(stop : kmb.Stop /* this doesn't work */) {
                this.stop = stop;
            }
            // some methods referencing kmb
        };
    }
}

Instead I have to use a dummy variable to make the type-check passing:

export default class Kmb {
    public readonly Stop; // inner class
    public readonly StopRoute; // inner class
    public constructor() {
        const kmb = this;
        this.Stop = class Stop {
            // some methods referencing kmb
        };
        const dummy_stop = this.Stop('', '', '', 0);
        this.StopRoute = class StopRoute {
            public readonly stop;
            public constructor(stop : typeof dummy_stop /* this works */) {
                this.stop = stop;
            }
            // some methods referencing kmb and this.stop
        };
    }
}

However I would like to avoid the use of a dummy variable, considering that the constructor call may have side-effect in my code. How can I eliminate dummy_stop in the above example?

Upvotes: 0

Views: 98

Answers (1)

Michael Tsang
Michael Tsang

Reputation: 781

Use InstanceType with array access syntax.

export default class Kmb {
    public readonly Stop; // inner class
    public readonly StopRoute; // inner class
    public constructor() {
        const kmb = this;
        this.Stop = class {
            // some methods referencing kmb
        };
        const dummy_stop = this.Stop('', '', '', 0);
        this.StopRoute = class {
            public readonly stop;
            public constructor(stop : InstanceType<Kmb["Stop"]>) {
                this.stop = stop;
            }
            // some methods referencing kmb and this.stop
        };
    }
}

Upvotes: 1

Related Questions