gpt4 book ai didi

javascript - 为什么我不能在 RxJs 6 中减少到不同的类型?

转载 作者:行者123 更新时间:2023-11-30 19:50:39 24 4
gpt4 key购买 nike

下面的示例不能作为版本 5 中链式运算符的直接转换。它给出了 Typescript 编译器错误。

from([1, 2]).pipe(
reduce((acc, curr) => {
return acc + ' ';
}, '')
);

Argument of type 'MonoTypeOperatorFunction' is not assignable to parameter of type 'OperatorFunction'. Types of parameters 'source' and 'source' are incompatible. Type 'Observable' is not assignable to type 'Observable'. Type 'number' is not assignable to type 'string'. [2345]

最佳答案

所以这是一个工作版本

from([1, 2])
.pipe(
reduce<number, string>(
(acc, curr) => {
return acc + ' ';
}, '')
).subscribe(x => {
console.log(x);
});

现在稍微解释一下,这里的问题来自这一行(来自 rxjs 源代码)并定义了函数签名(类型)

export function reduce<T>(accumulator: (acc: T, value: T, index: number) => T, seed?: T): MonoTypeOperatorFunction<T>;

所以在你的情况下,因为你没有明确地拒绝类型,rxjs 认为 accvalue 来自同一类型(number 在你的例子中,因为你传递的是数字数组)

通过显式拒绝函数参数的类型,我们解决了这个问题,因为我们在某种程度上帮助 rxjs/ts 使用下面适当的函数签名(这样就不会抛出错误)

export function reduce<T, R>(accumulator: (acc: R, value: T, index: number) => R, seed?: R): OperatorFunction<T, R>;

Here is the reduce source

如果我们必须总结一下,问题是 rxjs/ts 需要一些明确的类型帮助。

关于javascript - 为什么我不能在 RxJs 6 中减少到不同的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54502546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com