Skip to content

Commit 450f265

Browse files
committed
add type decoration utilities
1 parent 5821568 commit 450f265

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

types/utility.d.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,26 @@ type IfEquals<T, U, Y = true, N = false> =
4040
(<G>() => G extends T ? 1 : 0) extends
4141
(<G>() => G extends U ? 1 : 0) ? Y : N;
4242

43+
/**
44+
* @summary Extracts 'this' parameter from a function, if it exists. Otherwise, returns fallback.
45+
* @param {T} T Function type to extract 'this' parameter from.
46+
* @param {F} F Fallback type to return if 'this' parameter does not exist.
47+
*/
48+
type ThisParameter<T, F> = T extends { (this: infer This): void }
49+
? This
50+
: F;
51+
52+
/**
53+
* @summary Decorates all functions in an object with 'this' parameter.
54+
* @param {T} T Object with functions as values to add 'D' parameter to as 'this'. {@link D}
55+
* @param {D} D The type to be added as 'this' parameter to all functions in {@link T}.
56+
*/
57+
type AddThisParameter<T, D> = {
58+
[K in keyof T]: T[K] extends (...args: infer A) => infer R
59+
? ThisParameter<T[K], unknown> extends unknown
60+
? (this: D, ...args: A) => R
61+
: T[K]
62+
: T[K];
63+
};
64+
4365
}

0 commit comments

Comments
 (0)