At the moment, TypeScript does not have a built-in internal
access modifier. One workaround is to utilize an escape hatch for accessing protected
/private
class members:
class Foo {
protected f1 = "f1"
}
class Foo2 {
protected f2 = "f2"
public doSomething(foo: Foo) {
foo["f1"] // this works
}
}
You can access a protected
member from another class using bracket notation.
This workaround effectively conceals protected
members from external classes in most cases. If classes like Foo
and Foo2
are closely related within the same package, they might need to know certain implementation details of each other, such as the name of a protected property. Therefore, this approach can be considered architecturally sound.
To enhance security further, you could create separate types for Foo
and Foo2
that define only the public API accessible to clients:
class Foo implements FooPublic {
publicProp = 42
protected foo = "foo"
}
interface FooPublic {
publicProp: number // only publicProp is exposed to clients
}
Additionally, there is an ESLint rule named import/no-internal-modules
, which prohibits clients from directly importing your actual class from a sub-module.