File tree Expand file tree Collapse file tree 2 files changed +30
-4
lines changed Expand file tree Collapse file tree 2 files changed +30
-4
lines changed Original file line number Diff line number Diff line change 22/* eslint-disable react-hooks/exhaustive-deps */
33import * 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
Original file line number Diff line number Diff line change @@ -9,6 +9,7 @@ import useMobile from '../src/hooks/useMobile';
99import useState from '../src/hooks/useState' ;
1010import useSyncState from '../src/hooks/useSyncState' ;
1111import useControlledState from '../src/hooks/useControlledState' ;
12+ import useEvent from '../src/hooks/useEvent' ;
1213
1314global . 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} ) ;
You can’t perform that action at this time.
0 commit comments