given this code:
给定此代码:
/**
* Create a stream from an array of car objects.
*/
from([
{ name: 'Porsche', model: '911' },
{ name: 'Porsche', model: '911' },
{ name: 'Ferrari', model: 'F40' }
]).pipe(
/**
* Use keySelectorFn to return car names for use in comparison
*/
distinctUntilChanged(null, (car) => car.name)
)
.subscribe(console.log);
// console output:
// {name: "Porsche", model: "911"}
// {name: "Ferrari", model: "F40"}
TS complains that Argument of type 'null' is not assignable to parameter of type '(previous: unknown, current: unknown) => boolean'
.
TS报告类型为‘Null’的参数不能赋值给类型为‘(Previor:Uncern,Current:Uncern)=>Boolean’的参数。
If I change it to undefined
, the same error.
如果我将其更改为未定义,则会出现相同的错误。
Even in the rxjs docs is undefined
used:
即使在rxjs文档中也未定义使用:
// A stream of updates to a given account
const accountUpdates$ = of(
{ updatedBy: 'blesh', data: [] },
{ updatedBy: 'blesh', data: [] },
{ updatedBy: 'ncjamieson', data: [] },
{ updatedBy: 'ncjamieson', data: [] },
{ updatedBy: 'blesh', data: [] }
);
// We only want the events where it changed hands
const changedHands$ = accountUpdates$.pipe(
distinctUntilChanged(undefined, update => update.updatedBy)
);
In this code example I also get the same error.
在此代码示例中,我也收到了相同的错误。
So, the question is: how to set the comparer function to null/undefined without error?
因此,问题是:如何将比较器函数设置为空/未定义而不出错?
My TS version is 4.9.3. RxJs version is 7.5.0.
我的TS版本是4.9.3。RxJs版本为7.5.0。
更多回答
I have added it to the question at the end.
我已经把它加到了问题的末尾。
优秀答案推荐
This looks like it may be a quirk in the typing for distinctUntilChanged
. The error would probably go away if you disabled strictNullChecks
in your tsconfig.json
file.
这看起来可能是differtUntilChanged的输入过程中的一个怪癖。如果您在tsfig.json文件中禁用了strictNullChecks,该错误可能会消失。
However, you can just use distinctUntilKeyChanged
instead:
但是,您可以只使用DistertUntilKeyChanged:
distinctUntilKeyChanged('name');
distinctUntilChanged((prev:any,curr:any) => prev.name === curr.name)
更多回答
我是一名优秀的程序员,十分优秀!