How to return the callback return-type of the function in typescript and rxjs?

Viewed 47

I made a factory function which take callback and can extend the pipeline of the subject.

How do I replace Observable<unknown> to get the correct type in subscribe function?

import './style.css';
console.clear();

import { of, map, tap, Observable, Subject } from 'rxjs';

const createSubject = <T>(
  factoryFn: ($: Observable<T>) => Observable<unknown>
) => {
  const sub = new Subject<T>();

  const r = factoryFn(sub.asObservable());

  function trigger(value: T) {
    sub.next(value);
  }

  trigger.$ = r;

  return trigger;
};

const login = createSubject<{ username: string }>(($) => {
  const temp = $.pipe(
    tap(() => {
      console.log('in subject!!!');
    }),
    map(({ username }) => ({ username, id: 1, password: 'password' }))
  );

  // typescript is know about temp type.
  // Observable<{  username: string;  id: number; password: string; }>
  return temp; // and it's returning.
});

login.$.subscribe((r) => {
  console.log({ r });
});

login({ username: 'username' });

I have try those types but none of them works:

const createSubject = <T>(
  factoryFn: ($: Observable<T>) => ReturnType<typeof factoryFn>
) => {

const createSubject = <T>(
  factoryFn: <ReturnType = U>($: Observable<T>) => U
) => {

const createSubject = <T>(
  factoryFn: <U>($: Observable<T>) => Observable<U>
) => {

const createSubject = <T>(
  factoryFn: ($: Observable<T>) => ReturnType
) => {

I want typescript will know about the return of the callback by itself.

stackblitz

1 Answers

This pretty much tells compiler to forget caring about returned observable type:

factoryFn: ($: Observable<T>) => Observable<unknown>

You could add a Type parameter (R) that would be linked to input(T) via the function:

const createSubject = <T,R>(
  factoryFn: ($: Observable<T>) => Observable<R>
) => {
....
}

StackBlitz Fork

The compiler cannot execute the code and see types itself. It only uses the information that you provide it.

Related