Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda