Utilizing nested classes in TypeScript is achieved through the following code snippet:
class Parent {
private secret = 'this is secret'
static Child = class {
public readSecret(parent: Parent) {
return parent.secret
}
}
}
This approach is inspired by this answer. It enables the Child
class to access private properties of the Parent
class.
To define a variable with the nested class type, one might first attempt the following:
type NestedType = Parent.Child
const child: NestedType = new Parent.Child()
However, an error is encountered:
'Parent' only refers to a type, but is being used as a namespace here. ts(2702)
An alternative using the typeof
operator also proves unsuccessful:
type NestedType = typeof Parent.Child
const child: NestedType = new Parent.Child()
Ultimately, success is found in this revised approach:
const nestedTemplate = new Parent.Child()
type NestedType = typeof nestedTemplate
const child: NestedType = new Parent.Child()
Despite resolving the issue, this method does create an unnecessary instance of Child
. Is this a limitation of the TS language?
Additionally, exploration was done with namespaces:
class Parent {
private secret = 'this is secret'
}
namespace Parent {
export class Child {
public readSecret(parent: Parent) {
return parent.secret
}
}
}
Unfortunately, utilizing namespaces results in the Child
class losing access to the private properties of the Parent
class:
Property 'secret' is private and only accessible within class 'Parent'. ts(2341)