In RxJS until versions 6.x the method _subscribe in Subject.ts was @deprecated, but thus still accessible. In a project I’m working on, someone took that as a reason to override this method, in order to do stuff, when someone is subscribing to that Subject. Now, in newer versions (7.x) the method is protected and @internal. Since my class is extending the Subject class, I assume the fact that it’s protected shouldn’t make a difference. However, I can’t override it any more:
Error: src/app/common/util/updatable-subject.ts:42:11 - error TS4117: This member cannot have an 'override' modifier because it is not declared in the base class 'Subject<T>'. Did you mean 'subscribe'?
42 override _subscribe(subscriber: Subscriber<T>) {
~~~~~~~~~~
Error: src/app/common/util/updatable-subject.ts:43:30 - error TS2551: Property '_subscribe' does not exist on type 'Subject<T>'. Did you mean 'subscribe'?
43 const subscription = super._subscribe(subscriber);
~~~~~~~~~~
node_modules/rxjs/dist/types/internal/Observable.d.ts:50:5
50 subscribe(observerOrNext?: Partial<Observer<T>> | ((value: T) => void)): Subscription;
~~~~~~~~~
'subscribe' is declared here.
So somehow, RxJS manages to hide the function by annotating it @internal? Which is weird, because I tried to reproduce it in a minimal example, which didn’t work:
// app.ts
import express from 'express';
import {B} from './B';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
new B().subscribe();
});
app.listen(port, () => {
return console.log(`Express is listening at http://localhost:${port}`);
});
// A.ts
export class A {
/**
* @internal
*/
protected _subscribe() {
console.log("A");
}
}
// B.ts
import {A} from './A';
export class B extends A {
override _subscribe() {
super._subscribe();
console.log("B");
}
subscribe() {
this._subscribe();
}
};
Logs
Express is listening at http://localhost:3000
A
B
when run with npx tsc && node dist/app.js and loaded in the browser (http://localhost:3000/). So how does RxJS hide the @internal _subscribe method? And is there a way to still override it? And if not, are there other ways of getting to know when (and with what arguments) that method is called in RxJS?
>Solution :
@internal methods are stripped when enabling the stripInternal option in the tsconfig.
What happens is that the function doesn’t appear anymore in the generated d.ts file so it’s not visible in the type definition.
I would stronly advise against trying to rely on private methods.