Skip to content

Commit 8a92785

Browse files
authored
chore: useEvent type support undefined (#706)
* chore: useEvent type support undefined * chore: update
1 parent 33ca7f7 commit 8a92785

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

src/hooks/useEvent.ts

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

5-
function useEvent<T extends Function>(callback: T): T {
6-
const fnRef = React.useRef<any>();
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 {
12+
const fnRef = React.useRef<T | undefined>(callback);
713
fnRef.current = callback;
814

9-
const memoFn = React.useCallback<T>(
10-
((...args: any) => fnRef.current?.(...args)) as any,
15+
const memoFn = React.useCallback(
16+
(...args: any[]) => fnRef.current?.(...args),
1117
[],
1218
);
1319

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)