Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

140
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda