diff --git a/index.d.ts b/index.d.ts new file mode 100644 index 0000000..d0b857c --- /dev/null +++ b/index.d.ts @@ -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; diff --git a/index.js b/index.js index ae3460f..5673c0e 100644 --- a/index.js +++ b/index.js @@ -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; diff --git a/index.test-d.ts b/index.test-d.ts new file mode 100644 index 0000000..86d44ae --- /dev/null +++ b/index.test-d.ts @@ -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(mimickedFn); + +expectType(mimickedFn('bar')); +expectType(mimickedFn.unicorn); diff --git a/package.json b/package.json index 118b89c..ae44907 100644 --- a/package.json +++ b/package.json @@ -13,10 +13,11 @@ "node": ">=6" }, "scripts": { - "test": "xo && ava" + "test": "xo && ava && tsd-check" }, "files": [ - "index.js" + "index.js", + "index.d.ts" ], "keywords": [ "function", @@ -34,7 +35,8 @@ "change" ], "devDependencies": { - "ava": "*", - "xo": "*" + "ava": "^1.3.1", + "tsd-check": "^0.3.0", + "xo": "^0.24.0" } }