One of my functions serves as a shortcut for selecting values from synchronous observable streams.
The function in its entirety looks like this:
export function select<T>(inStream: Observable<T>): T {
let value: T;
race(
inStream,
throwError(
new Error(
select.name + " expects a synchronous stream. Received an asynchronous stream."
)
)
)
.pipe(take(1))
.subscribe(val => {
value = val;
});
return value;
}
The function behaves correctly and will raise an error if the inStream is not synchronous, which means I will either receive the current/latest emitted value OR an error.
However, TypeScript raises a concern about using the value before it's assigned. While I understand that TypeScript may not fully recognize how I'm enforcing synchronicity or an error condition, practical tests indicate that the value will always be properly set when the stream is indeed synchronous, or an error will occur.
How can I address this particular TypeScript issue more elegantly? I am hesitant to use an ignore directive unless there are better suggestions available.
Thank you!
(I have provided a demo showcasing the functionality working as intended so we can concentrate on resolving the TypeScript matter without getting sidetracked by the code implementation:
https://stackblitz.com/edit/rxjs-select-demo?file=index.ts
In this example, the 'select' function is invoked twice. The first time on a synchronous stream retrieves the value successfully. When used on an asynchronous stream for the second time, an error is thrown with no returned value. This demonstrates the desired behavior.)