0
votes

I am trying to use rxjs in typescript for one of my projects and am struggling with typing one function. The function I am trying to give a type (Return value type) is createMessageSource.

import { interval, Subscription, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

type MessageType = {
      name: string;
      content: string;
}

const createMessageSource =
      (period: number, name: string, content: string) =>
        interval(period)
          .pipe(map(i => ({
            name,
            content: `${content} - ${i}`,
          })));

As far as I understand the problem, the return value of the pipe command should be an Observable or a Subscription. So I tried the following types so far:

const createMessageSource: Observable<MessageType[]> = ...

const createMessageSource: Subscription = ...

Both combinations end in the following typescript error shown in vscode:

Type '(period: number, name: string, attribute: string) => Observable<{ name: string; content: number; }>' is missing the following properties from type 'Observable<MessageType[]>': _isScalar, source, operator, lift, and 6 more.ts(2740)

Thx for the help beforehand

1
Correct type for createMessageSource is Observable<MessageType> because your code doesn't emit arrays but single objects. - martin

1 Answers

1
votes

It's true that .pipe() returns an Observable. Your problem is that createMessageSource is not an Observable, but a Function that returns an Observable :-)

So you could define a new MessageFactory type:

type MessageSourceFactory = (period: number, name: string, content: string) => Observable<MessageType>;


const createMessageSource: MessageSourceFactory =
      (period: number, name: string, content: string) =>
        interval(period).pipe(
          map(i => ({
            name,
            content: `${content} - ${i}`,
          }))
        );

or you could define it like a function, if that suits your needs:

function createMessageSource(period: number, name: string, content: string): Observable<MessageType> {
  return interval(period).pipe(
    map(i => ({
      name,
      content: `${content} - ${i}`,
    }))
  );
}