While exploring Typescript, I came across a way to mimic module visibility using interfaces as discussed in this Github comment. However, I am unsure if it is feasible to achieve the same in a specific scenario:
abstract class ConnectionTarget
{
// callback that subclasses must implement
protected abstract onConnection: (conn: Connection) => void;
// property that must be accessible 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);
}
}
// function requiring access to private members
// parameter is a user-provided subclass of ConnectionTarget
function doMagicThings(target: ConnectionTarget, source: ConnectionSource)
{
// perform magic operations here ...
// method that should be module-protected, like addConnection
let aConnection: source.createConnection();
target.addConnection(aConnection);
}
I want users to extend ConnectionTarget
, mandating implementation of onConnection
while only being able to utilize the connections
property, with everything else concealed from 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());
}
}