rxjs5 - typescript esto como parámetro
Cuando estaba revisando la biblioteca rxjs me encontré con esta función:
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));
}
fuente: https://github.com/ReactiveX/rxjs/blob/master/src/operator/map.ts
Me pregunto qué sucede realmente al pasar un argumento llamado this. ¿Se trata simplemente como cualquier otro parámetro o Typescript realiza alguna acción especial cuando haces esto?
Respuesta #1
No se puede pasar directamente a map un argumento que corresponda al parámetro this en la firma. El parámetro this es utilizado por TypeScript para indicar el tipo del contexto y no hay un argumento correspondiente en tiempo de ejecución.
Sin embargo, la función map puede ser llamada usando Function.prototype.call o Function.prototype.apply, y el contexto puede ser pasado a call o apply.
Por ejemplo:
import { of } from "rxjs/observable/of";
import { map } from "rxjs/operator/map";
const source = of(1);
const mapped = map.call(source, value => value + 1);
En este ejemplo, source correspondería a this en la implementación de map, y tendría el tipo Observable<number>.
Para más información, consulte la sección "this parámetros" en la documentación.
