为什么我在pipe
函数中丢失了类型?如何解决这个问题?
属性'n'在类型'{}'上不存在
stackblitz
import { of, map, Observable, Subject, pipe, tap } from 'rxjs';
import { exhaustMap, withLatestFrom } from 'rxjs/operators';
const action = new Subject<{ n: number }>();
const id$ = of(1);
const bar = () =>
pipe(
withLatestFrom(id$),
exhaustMap(([{ n }, id]) => of([n, id])), // <--- Property 'n' does not exist on type '{}'
tap(() => {
console.log('in bar pipeline');
})
);
const foo = action.pipe(bar());
foo.subscribe();
action.next({ n: 1 });
pipe
根据传递的参数推断所有类型。看看https://github.com/ReactiveX/rxjs/blob/master/src/internal/util/pipe.ts
尝试为所有自动推理的第一个参数指定类型。
withLatestFrom<{ n: number }, number[]>(id$),
添加合适的数据类型:
const bar = () =>
pipe(
withLatestFrom(id$),
exhaustMap(([{ n }, id]: [ {n: number}, number ]) => of([n, id]))
tap(() => {
console.log('in bar pipeline');
})
);