Brendan
Brendan

Reputation: 19353

Refer to a nested class in parent class in Typescript

I'm trying to create a nested class mostly because the nested classes only need to be used inside the parent. I've tried the following ...

class Foo {
  static Bar = class {}

  myBar: Foo.Bar // This gives "'Foo' refers to a type but is being used as a namespace here"
}

const bar = new Foo.Bar() // This is OK

... but as the comment says, this doesn't work when used as a type inside the parent. Is there a correct way to reference that I am missing?

I'm using Typescript 4.1.3

Upvotes: 2

Views: 884

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42170

Bear with me, because the type for this is more complicated than you might think.

The name Foo refers to the class variable itself and also to the type for an instance of the Foo class. Calling new Foo.Bar() is fine because you accessing .Bar on the variable Foo. You cannot access .Bar on the type Foo because that is not how you access properties in typescript. Dot notation is used only for namespaces, which is why you get the error "'Foo' refers to a type but is being used as a namespace here".

The syntax for accessing properties is Foo['Bar']. But this doesn't work either because the type Foo refers to an instance of the class rather than to the class itself. Bar is a static property, so it does not exist on the instance. As explained here, we need to use typeof Foo to get the type for the class constructor Foo.

So now we try (typeof Foo)['Bar'] and we are almost there, except that this returns the type for the class constructor of Bar and we (presumably) want the type for an instance. So finally we arrive at the type:

InstanceType<(typeof Foo)['Bar']>

Typescript Playground Link

Upvotes: 6

Related Questions