Created
June 23, 2024 02:56
-
-
Save kbjr/11d3ec0f25d0dd1a84191d5782c25183 to your computer and use it in GitHub Desktop.
`Function.bind` in TypeScript with typing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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