ReactiveX / rxjs

A reactive programming library for JavaScript
https://rxjs.dev
Apache License 2.0
30.73k stars 3k forks source link

(TypeScript limitation?) scan typings still not completely accurate #6649

Open benlesh opened 3 years ago

benlesh commented 3 years ago

Frequently, a user may want to initialize state with some initial value so the scan is called on each pass, but the reducer will never return that value type.

In this scenario the types still come out wrong:

import { of, scan } from 'rxjs';

// result$ should be type `Observable<number>`, but is `Observable<number | null>`
const result$ = of(1, 2, 3).pipe(
  scan((state, value) => {
    return (state ?? 0) + value;
  }, null as number | null)
);

result$.subscribe(console.log); // 1, 3, 6

Or maybe it's this, which will have all sorts of type errors:

import { of, scan, map } from 'rxjs';

const result$ = of(1, 2, 3).pipe(
  scan((state, value) => {
     if (state.type === 'init') {
        return { type: 'first', message: `First we got ${value}` };
     } else {
        return { type: 'update', message: `${state.message}, then we got ${value}` };
     }
  }, { type: 'init' }),
  map(({ message }) => message + '.'),
)

result$.subscribe(console.log);

/*
First we got 1.
First we got 1, then we got 2.
First we got 1, then we got 2, then we got 3.
*/
benlesh commented 3 years ago

This is apparently a limitation of TypeScript, and there's nothing we can really do here, AFAICT. cc @DanielRosenwasser: Just to be sure, there's not really a way to do this with TypeScript is there? Array reduce seems to have similar issues.

console.log([1, 2, 3].reduce((acc, value) => {
    if (acc === null) {
        return '' + value;
    } else {
        return acc + ', ' + value;
    }
}, null))

https://www.typescriptlang.org/play?ssl=7&ssc=10&pln=1&pc=1#code/MYewdgziA2CmB00QHMAUBtAjAGgAQCY8BmAXXgCdYATAV2FlVQENhg8A3J6G2ASlwC8APlwBvALAAoXDNwBLAGa5mrQQIG4wNaNH4Tpsw5QAuNcmFwByS7gDUuTt1gBuKYYC+uWNAiwxbw1kTMwsWYDsrPBt7Rx5XAxl3KXc8LR1eXiA

I searched here, but didn't see anything: https://github.com/microsoft/TypeScript/issues?q=is%3Aissue+is%3Aopen+%22reduce%22+label%3A%22Design+Limitation%22+

benlesh commented 3 years ago

If filed a related issue at https://github.com/microsoft/TypeScript/issues/46438 for the TypeScript team to track it. I'm sure they must know about this, but I didn't see an issue where it was being tracked.