Skip to content

Commit 9cc997f

Browse files
committed
Improve typing of 'bind' method on function types
1 parent 34d9d4b commit 9cc997f

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/lib/es5.d.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,16 @@ interface FunctionConstructor {
295295

296296
declare const Function: FunctionConstructor;
297297

298+
/**
299+
* Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter.
300+
*/
301+
type ThisParameterType<T> = T extends (this: unknown, ...args: any[]) => any ? unknown : T extends (this: infer U, ...args: any[]) => any ? U : unknown;
302+
303+
/**
304+
* Removes the 'this' parameter from a function type.
305+
*/
306+
type OmitThisParameter<T> = unknown extends ThisParameterType<T> ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T;
307+
298308
interface CallableFunction extends Function {
299309
/**
300310
* Calls the function with the specified object as the this value and the elements of specified array as the arguments.
@@ -317,7 +327,7 @@ interface CallableFunction extends Function {
317327
* @param thisArg The object to be used as the this object.
318328
* @param args Arguments to bind to the parameters of the function.
319329
*/
320-
bind<T, A extends any[], R>(this: (this: T, ...args: A) => R, thisArg: T): (...args: A) => R;
330+
bind<T>(this: T, thisArg: ThisParameterType<T>): OmitThisParameter<T>;
321331
bind<T, A0, A extends any[], R>(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R;
322332
bind<T, A0, A1, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R;
323333
bind<T, A0, A1, A2, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R;
@@ -347,7 +357,7 @@ interface NewableFunction extends Function {
347357
* @param thisArg The object to be used as the this object.
348358
* @param args Arguments to bind to the parameters of the function.
349359
*/
350-
bind<A extends any[], R>(this: new (...args: A) => R, thisArg: any): new (...args: A) => R;
360+
bind<T>(this: T, thisArg: any): T;
351361
bind<A0, A extends any[], R>(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R;
352362
bind<A0, A1, A extends any[], R>(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R;
353363
bind<A0, A1, A2, A extends any[], R>(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R;

0 commit comments

Comments
 (0)