简体   繁体   English

当使用多个 pipe typescript 时 RXJS 类型推理如何工作

[英]How RXJS type inference work when multiple pipe is used typescript

const of = require('rxjs').of;
const map = require('rxjs/operators').map

of(123).pipe(
  map(num => num.toString()),
  map(str => str.substring(0,1)),
).subscribe(console.log);

In the second map above, the type of str parameter is correctly inferred from the previous map that returns a string .在上面的第二个map中, str参数的类型是从前面返回stringmap正确推断的。 I am curious how typescript is inferring the type in the second map operator.我很好奇 typescript 如何推断第二个 map 运算符中的类型。

Is this RxJS who nicely designed the code so that it can happen?这个 RxJS 是否精心设计了代码以使其发生?
Or is it just VS code that has special IntelliSense for RxJS?还是只是 VS 代码对 RxJS 具有特殊的 IntelliSense?

I'd say it is all handled by RxJS.我想说这一切都由 RxJS 处理。

Looking at the pipe overloads查看pipe过载

pipe(): Observable<T>;
  pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;
  pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;
  pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;
...

we can see that there's a lot going on.我们可以看到发生了很多事情。

OperatorFunction<T, A> type refers to a function whose single parameter is an Observable of type T and whose return type is also an Observable of type A : OperatorFunction<T, A>类型指的是 function ,其单个参数是T类型的Observable ,其返回类型也是A类型的 Observable :

export interface OperatorFunction<T, R> extends UnaryFunction<Observable<T>, Observable<R>> {}

Let's also have a look at map 's signature我们也来看看map的签名

export function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> { ... }

As you can see, its return type will be a function that receives an observable and returns another observable.正如你所看到的,它的返回类型将是一个 function,它接收一个 observable 并返回另一个 observable。 In this case, the type of the returned Observable ( R ) is inferred from the provided projection function: (value: T, index: number) => R在这种情况下,返回的 Observable类型R )是从提供的投影 function推断出来的:( (value: T, index: number) => R

So, if you have所以,如果你有

const src$ = of(1).pipe(map(v => '' + v));

src$ will be an observable whose type T will be string . src$将是一个类型Tstring的 observable。

And here's why type inference also works inside subscribe :这就是为什么类型推断也适用于subscribe

subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription; // Providing callbacks

subscribe(observer?: PartialObserver<T>): Subscription; // Providing an observer object

where T is the inferred type of the Observable(ie from map 's provided fn in this case).其中T是 Observable 的推断类型(即在这种情况下来自map提供的 fn )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM