Pace
Pace

Reputation: 43867

Typescript cast to void for Observable

I have a class like so:

class Consumer {
  consume(event: Observable<void>) {
    event.subscribe(() => console.log('Something happened'));
  }
}

My source observable is not void:

const obs = Observable.interval(1000);

The two clumsy solutions I could come up with for consuming the observable are:

// Bad (wasteful call to map)
consumer.consume(obs.map(() => {}));
// Bad (confusing syntax)
consumer.consume(obs as any as Observable<void>);

What is the best way to cast my observable to Observable<void> so I can consume it?

Upvotes: 2

Views: 2045

Answers (2)

kotoole
kotoole

Reputation: 1746

A generic type on the function covers this case well:

class Consumer {
  consume<X>(event: Observable<X>) {
    event.subscribe(() => console.log('Something happened'));
  }
}

Note that the direct "fix" of using Observable<any> sacrifices type safety. For instance, it allows the implementation

consume(event: Observable<any>) {
  event.subscribe((value) => value.literallyAnyMethod());
}

...without any compiler errors. This situation (and many like it) have prompted many codebases to implement rules disallowing any.

I don't believe TypeScript has single, non-generic type which allows your safe implementation but not my unsafe implementation, so the generic type X, though unused, is the right solution.

Upvotes: 2

ethan.roday
ethan.roday

Reputation: 2635

It sounds like what you want is not Observable<void>, but Observable<any>. That will allow you to pass any observable into consume(). If you really must cast, then as any as Observable<void> is probably your best bet.

Upvotes: 1

Related Questions