Skip to content

Instantly share code, notes, and snippets.

@kbjr
Created June 23, 2024 02:56
Show Gist options
  • Save kbjr/11d3ec0f25d0dd1a84191d5782c25183 to your computer and use it in GitHub Desktop.
Save kbjr/11d3ec0f25d0dd1a84191d5782c25183 to your computer and use it in GitHub Desktop.
`Function.bind` in TypeScript with typing
export interface Fn<T, P extends any[], R> {
(this: T, ...args: P) : R;
}
export type UnboundParams<F extends Fn<any, [ ...BindP, ...any[] ], any>, BindP extends any[]>
= F extends Fn<any, [ ...BindP, ...infer CallP ], any> ? CallP : never;
export type BoundFn<F extends Fn<any, [ ...BindP, ...any[] ], any>, BindP extends any[]>
= F extends Fn<infer T, [ ...BindP, ...infer CallP ], infer R>
? Fn<T, CallP, R>
: never;
export function bind<
T,
R,
BindP extends any[],
F extends Fn<T, [ ...BindP, ...UnboundParams<F, BindP> ], R>,
>(fn: F, this_val: T, ...params: BindP) : BoundFn<F, BindP> {
return fn.bind(this_val, ...params);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment