打字稿为参
问题描述:
当我一直在寻找通过我碰到这个功能跌跌撞撞rxjs库:打字稿为参
export function map<T, R>(this: Observable<T>, project: (value: T, index: number) => R, thisArg?: any): Observable<R> {
if (typeof project !== 'function') {
throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
}
return this.lift(new MapOperator(project, thisArg));
}
来源:https://github.com/ReactiveX/rxjs/blob/master/src/operator/map.ts
我在想传递一个名为this
参数时到底发生了什么。 它只是像对待任何其他参数一样对待,或者当你这样做时打印一些特别的动作?
答
您不能直接传递map
参数,该参数对应于签名中的参数this
。 TypeScript使用this
参数指示上下文的类型,并且在运行时没有相应的参数。
然而,map
功能可使用Function.prototype.call
或Function.prototype.apply
被调用,并且上下文可以被传递到call
或apply
。
例如:
import { of } from "rxjs/observable/of";
import { map } from "rxjs/operator/map";
const source = of(1);
const mapped = map.call(source, value => value + 1);
在这个例子中,source
将对应于在this
的map
实施,它将有类型Observable<number>
。
有关详细信息,请参阅documentation中的“this
参数”一节。