|
1 | | -export function spy<A extends any[], R, This>( |
2 | | - fn: (this: This, ...args: A) => R, |
3 | | - before?: ((this: This, ...args: A) => void) | null, |
4 | | - after?: ((this: This, result: R, ...args: A) => void) | null |
5 | | -): (this: This, ...args: A) => R { |
6 | | - return function (this: This, ...args: A): R { |
| 1 | +export type SafeReturnType<F> = F extends (...args: any[]) => infer R |
| 2 | + ? R |
| 3 | + : undefined; |
| 4 | + |
| 5 | +export type SafeParameters<F> = F extends (...args: infer P) => any ? P : []; |
| 6 | + |
| 7 | +export function spy<F extends (this: This, ...args: any[]) => any, This>( |
| 8 | + fn: F, |
| 9 | + before?: ((this: This, ...args: Parameters<F>) => void) | null, |
| 10 | + after?: |
| 11 | + | ((this: This, result: ReturnType<F>, ...args: Parameters<F>) => void) |
| 12 | + | null |
| 13 | +): (this: This, ...args: Parameters<F>) => ReturnType<F>; |
| 14 | +export function spy< |
| 15 | + F extends ((...args: any[]) => any) | null | undefined, |
| 16 | + This |
| 17 | +>( |
| 18 | + fn: F, |
| 19 | + before?: ((this: This, ...args: SafeParameters<F>) => void) | null, |
| 20 | + after?: |
| 21 | + | (( |
| 22 | + this: This, |
| 23 | + result: SafeReturnType<F>, |
| 24 | + ...args: SafeParameters<F> |
| 25 | + ) => void) |
| 26 | + | null |
| 27 | +): (this: This, ...args: SafeParameters<F>) => SafeReturnType<F>; |
| 28 | +export function spy( |
| 29 | + this: any, |
| 30 | + fn: any, |
| 31 | + before?: any, |
| 32 | + after?: any |
| 33 | +): (...args: any[]) => any { |
| 34 | + return function (this: any, ...args: any[]): any { |
7 | 35 | if (typeof before === "function") { |
8 | 36 | before.apply(this, args); |
9 | 37 | } |
10 | 38 |
|
11 | | - const result = fn.apply(this, args); |
| 39 | + const result = typeof fn === "function" ? fn.apply(this, args) : undefined; |
12 | 40 |
|
13 | 41 | if (typeof after === "function") { |
14 | 42 | after.call(this, result, ...args); |
|
0 commit comments