Skip to content
Advertisement

Get the type of a nested class in TypeScript

I’m using nested classes in TypeScript by using the following code:

JavaScript

This is based on the following answer. It allows my Child class to access private properties of the Parent class.

I want to type a variable with the nested class type, I started naïvely with the following code:

JavaScript

But I get the following error:

JavaScript

I tried to use the typeof operator:

JavaScript

But it doesn’t work:

JavaScript

Finally I was able to make it work:

JavaScript

However, this code creates a useless instance of Child. Is this a limitation of the TS language?

FYI, I also tried by using namespaces:

JavaScript

But then the Child class is no longer able to access the private properties of the Parent class:

JavaScript

Advertisement

Answer

Using the typeof child prototype should be enough to resolve your typings trouble.

JavaScript

You can test it there Playground Link

That way you do not have to instantiate any intermediary classes.

Advertisement