I saw that in Typescript you can emulate module visibility with interfaces, but I don't know if it is possible to achieve it in the following scenario:
abstract class ConnectionTarget
{
// callback that subclasses must implement
protected abstract onConnection: (conn: Connection) => void;
// property that must be available to subclasses
protected get connections(): Readonly<Iterable<Connection>>
{
return this.conns;
}
// private field needed for previous property
private conns: Connection[] = [];
// method that SHOULD HAVE MODULE VISIBILITY
// my module should be able to add connections,
// but my users shouldn't
private addConnection(conn: Connection)
{
this.conns.push(conn);
this.onConnection(conn);
}
}
// my function that needs access to the private members
// the parameter is a user-provided subclass of ConnectionTarget
function doMagicThings(target: ConnectionTarget, source: ConnectionSource)
{
// do magic tricks here ...
// method that should be module-protected, like addConnection
let aConnection: source.createConnection();
target.addConnection(aConnection);
}
I'd like my users to extend ConnectionTarget, having to implement onConnection and being able to only use the property connections, with everything else hidden to them.
EDIT: example usage
// class in user code
class MyConnectionTarget extends ConnectionTarget
{
// users must implement this abstract method
onConnection(conn: Connection)
{
// user specific code here
// ...
// can use property 'connections'
console.log(this.connections)
// should error here:
// should not allow to use the following method
this.addConnection(new Connection());
}
}
ConnectionTargetshouldn't be able to access private methods/members.addConnectionvisible to other things in my module. Otherwise, I have no way to add connections to the class.