Skip to content

Commit

Permalink
Add TypeScript definition (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
BendingBender authored and sindresorhus committed Mar 7, 2019
1 parent 59f31c7 commit eeaf3fb
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 5 deletions.
15 changes: 15 additions & 0 deletions 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;
5 changes: 4 additions & 1 deletion 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;
18 changes: 18 additions & 0 deletions 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<typeof foo & {unicorn: string}>(mimickedFn);

expectType<boolean>(mimickedFn('bar'));
expectType<string>(mimickedFn.unicorn);
10 changes: 6 additions & 4 deletions package.json
Expand Up @@ -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",
Expand All @@ -34,7 +35,8 @@
"change"
],
"devDependencies": {
"ava": "*",
"xo": "*"
"ava": "^1.3.1",
"tsd-check": "^0.3.0",
"xo": "^0.24.0"
}
}

0 comments on commit eeaf3fb

Please sign in to comment.