Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
59f31c7
commit eeaf3fb
Showing
4 changed files
with
43 additions
and
5 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
/** | ||
* Make a function mimic another one. It will copy over the properties `name`, `length`, `displayName`, and any custom properties you may have set. | ||
* | ||
* @param to - Mimicking function. | ||
* @param from - Function to mimic. | ||
* @returns The modified `to`. | ||
*/ | ||
export default function mimicFn< | ||
ArgumentsType extends unknown[], | ||
ReturnType, | ||
FunctionType extends (...arguments: ArgumentsType) => ReturnType | ||
>( | ||
to: (...arguments: ArgumentsType) => ReturnType, | ||
from: FunctionType | ||
): FunctionType; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,11 @@ | ||
'use strict'; | ||
module.exports = (to, from) => { | ||
const mimicFn = (to, from) => { | ||
for (const prop of Reflect.ownKeys(from)) { | ||
Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); | ||
} | ||
|
||
return to; | ||
}; | ||
|
||
module.exports = mimicFn; | ||
module.exports.default = mimicFn; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import {expectType} from 'tsd-check'; | ||
import mimicFn from '.'; | ||
|
||
function foo(string: string) { | ||
return false; | ||
} | ||
foo.unicorn = '🦄'; | ||
|
||
function wrapper(string: string) { | ||
return foo(string); | ||
} | ||
|
||
const mimickedFn = mimicFn(wrapper, foo); | ||
|
||
expectType<typeof foo & {unicorn: string}>(mimickedFn); | ||
|
||
expectType<boolean>(mimickedFn('bar')); | ||
expectType<string>(mimickedFn.unicorn); |
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