Having trouble in typescript generic type declaration

Viewed 38

I'm creating a hook called useUpdate, having trouble declaring the type, the code shows below

type CallBack<T extends readonly any[]> = (
  ...args: T
) => void | (() => void | undefined);

function useUpdate<T extends readonly any[]>(
  callback: CallBack<T>,
  deps: T
) {
  const didMount = useRef(false);
  const prevDeps = useRef(deps);

  useEffect(() => {
    if (!didMount.current) {
      didMount.current = true;

      return;
    }

    const clean = callback(...prevDeps.current);

    prevDeps.current = deps;

    return () => {
      if (clean) {
        clean();
      }
    };
  }, deps);
}

when using it there's no problem if the callback has args, but if no args is provided for the callback, the type of deps will be incorrect

const state: boolean = useSomethingElse(); // get changable data from anywere else

// OK, no type error
useUpdate((prevState) => {
 console.log('I want to compare the current state and prevState', prevState, state);
},[state]);


useUpdate(() => {
 console.log('I only care about the current state', state);
},[state]); // Type error occurs on this line, the message is:
//  Argument of type '[boolean]' is not assignable to parameter of type '[]'.
//  Source has 1 element(s) but target allows only 0.ts(2345)

I know it's because TypeScript sets the T as callback args which is [] if the args are not provided, but is there any way to let TypeScript uses the type of deps and skips the type of callback args while setting the T?

1 Answers

Two ways you can fix this:

(1) Make deps the first parameter so it starts by inferring T from deps

(2) Use a second generic for callback:

function useUpdate<T extends readonly any[], Cb extends CallBack<T>>(
  callback: Cb,
  deps: T
) {
Related