DEV Community

Discussion on: TypeScript tip of the week - generics

Collapse
 
zanehannanau profile image
ZaneHannanAU

Here's one I use myself, which is super magical:

/** Moves the this parameter out of the called function */
//@ts-ignore
export const fbind = <F extends (this: T, ...args: any[]) => R, T, R>(fn: F): ((self: T, ...args: Parameters<F>) => R) => Function["prototype"]["call"]["bind"](fn)

(Note: the square brackets are for --mangle-props strict mode in terser)

this is a little better and acts only as a call function, but requires a reference so it's only useful on native callers like Array.prototype.push or MessagePort.prototype.postMessage, and makes it more of a take-by-reference function in rust. Modular functional programming if you will.