Skip to content

Commit 7eb618d

Browse files
committed
chore: update
1 parent 1d3ddda commit 7eb618d

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

src/hooks/useEvent.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,18 @@
22
/* eslint-disable react-hooks/exhaustive-deps */
33
import * as React from 'react';
44

5-
function useEvent<T extends (...args: any[]) => any>(
6-
callback: T | undefined,
7-
): T {
5+
function useEvent<T extends ((...args: any[]) => any) | undefined>(
6+
callback: T,
7+
): undefined extends T
8+
? (
9+
...args: Parameters<NonNullable<T>>
10+
) => ReturnType<NonNullable<T>> | undefined
11+
: T {
812
const fnRef = React.useRef<T | undefined>(callback);
913
fnRef.current = callback;
1014

1115
const memoFn = React.useCallback(
12-
((...args) => fnRef.current?.(...args)) as T,
16+
(...args: any[]) => fnRef.current?.(...args),
1317
[],
1418
);
1519

tests/hooks.test.tsx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import useMobile from '../src/hooks/useMobile';
99
import useState from '../src/hooks/useState';
1010
import useSyncState from '../src/hooks/useSyncState';
1111
import useControlledState from '../src/hooks/useControlledState';
12+
import useEvent from '../src/hooks/useEvent';
1213

1314
global.disableUseId = false;
1415

@@ -706,4 +707,23 @@ describe('hooks', () => {
706707
expect(container.textContent).toEqual('2');
707708
});
708709
});
710+
711+
describe('useEvent', () => {
712+
it('extract type', () => {
713+
const Demo = (props: {
714+
canUndefined?: (a: number) => boolean;
715+
notUndefined: (a: number) => boolean;
716+
}) => {
717+
const ua = useEvent(props.canUndefined);
718+
const ub = useEvent(props.notUndefined);
719+
720+
ua(1);
721+
ub(2);
722+
723+
return null;
724+
};
725+
726+
expect(Demo).toBeTruthy();
727+
});
728+
});
709729
});

0 commit comments

Comments
 (0)