RxJS distinctUntilChanged传入null/undefined时TS报错的解决方法
解决distinctUntilChanged传入null/undefined的类型错误问题
针对TypeScript 4.9.3、RxJS 7.5.0环境下的这个类型报错,有以下几种可行方案:
手动传入默认比较逻辑:如果想达到官方文档中传入null/undefined的效果(即使用默认的相等比较),可以直接传入
(prev, curr) => prev === curr作为comparer参数,这和不传参数的默认行为一致,同时符合TS类型要求。
示例(汽车对象流场景):import { of } from 'rxjs'; import { distinctUntilChanged } from 'rxjs/operators'; type Car = { brand: string }; const carStream = of<Car>({ brand: 'Toyota' }, { brand: 'Toyota' }, { brand: 'Honda' }); carStream.pipe( distinctUntilChanged((prev, curr) => prev.brand === curr.brand) ).subscribe(console.log);若为值类型流,直接传
(a, b) => a === b即可。使用类型断言绕过检查:如果必须显式传入null或undefined,可以通过类型断言告诉TypeScript忽略类型错误:
// 用any断言快速解决 carStream.pipe(distinctUntilChanged(null as any)).subscribe(console.log); // 或更精确的函数类型断言 carStream.pipe(distinctUntilChanged(undefined as (prev: Car, curr: Car) => boolean)).subscribe(console.log);升级RxJS版本:该问题属于RxJS 7.5.0的类型定义缺陷,后续版本(如7.6.0及以上)已修复此问题,升级后可直接传入null/undefined而不触发类型错误。
内容的提问来源于stack exchange,提问作者derstauner
相关产品推荐
相关产品推荐

