Rxjs: from() does not infer type correctly with TS 3.6

Created on 29 Aug 2019  路  9Comments  路  Source: ReactiveX/rxjs

Bug Report

Current Behavior

Type 'Observable<unknown>' is not assignable to type 'Observable<string>'.
  Type 'unknown' is not assignable to type 'string'.ts(2322)

Reproduction

function asObservable(input: string | ObservableInput<string>): Observable<string> {
    return typeof input === 'string' ? of(input) : from(input)
}

Expected behavior
Should compile

Environment

  • RxJS version: 6.5.2
  • TS version: 3.6.2

Possible Solution
Instead of using ObservedValueOf<T>:

export declare function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>

declare from like:

export declare function from<O>(input: ObservableInput<O>): Observable<O>

this seems to work.

Additional context/Screenshots
2019-08-29 10 49 04

All 9 comments

FWIW, I think the problem is that a string is also an ObservableInput<string>. This does not effect the same problem, AFAICT:

function asObservable(input: string | Promise<string>): Observable<string> {
  return typeof input === "string" ? of(input) : from(input);
}

What it is in TypeScript 3.6, that has effected this changed behaviour, IDK.

That is the reason we wrote the type switch in that helper, but still you'd expect ObservedValueOf<Promise<string>> to infer string, since Promise<string> should clearly only match the Promise<T> in ObservableInput<T>

Hard to see this as anything other than a TypeScript bug:

declare const i: ObservableInput<string>;
const r = from(i); // Observable<unknown>

And one that will pretty badly wreck the typings that will be even more widely used in v7. 馃槶

@benlesh ^

Yeah already filed in https://github.com/microsoft/TypeScript/issues/33131

But is there a need to use ObservedValueOf here?

But is there a need to use ObservedValueOf here?

I think there might be, yes:

https://github.com/ReactiveX/rxjs/commit/eb1d5963178f3062aca67340532349e93232ee27

Yes, specifically this doesn't work without it:

// from(Observable<A> | Observable<B>): Observable<A | B>
from(Math.random() > 0.5 ? of('123') : of(123));

This seems to be fixed in TypeScript 3.6.3.

Yep, can confirm it鈥檚 fixed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cartant picture cartant  路  3Comments

marcusradell picture marcusradell  路  4Comments

benlesh picture benlesh  路  3Comments

Zzzen picture Zzzen  路  3Comments

cartant picture cartant  路  3Comments