Search code examples
reactjstypescriptreact-hooksreact-spring

useSprings with TypeScript


function getDefaultOrder(items: any[]): number[] {
  return items.map((_, index) => index);
}

type SpringsHandler<T> = (index: number) => T;
type SpringValues = {
  zIndex: number,
  y: number,
  scale: number,
  shadow: number,
  immediate: boolean | ((v: string) => boolean),
};
function makeSpringsHandler(order: number[]): SpringsHandler<SpringValues> {
  return index => ({
    zIndex: 1,
    y: order.indexOf(index) * 50 + 30,
    scale: 1,
    shadow: 5,
    immediate: false,
  })
}

function useMySprings(items: any[]) {
  const order = useRef<number[]>([]);
  const [springs, setSprings] = useSprings(items.length, makeSpringsHandler(order.current));
  useEffect(() => {
    order.current = getDefaultOrder(items);
    setSprings(makeSpringsHandler(order.current)); // The error appears here "makeSpringsHandler(order.current)" cannot be the param for setSprings
  }, [items, setSprings]);

  return [springs];
}

So I want to create a custom hook that takes an array and returns the animated values using useSprings in TypeScript, but the compiler doesn't allow me to pass my handler function to setSprings.

And I receive the following error:

No overload matches this call.
  Overload 1 of 2, '(ds: Partial<Merge<{ zIndex: number; y: number; scale: number; shadow: number; immediate: boolean | ((v: string) => boolean); } & UseSpringBaseProps, { from?: Partial<Pick<{ zIndex: number; y: number; scale: number; shadow: number; immediate: boolean | ((v: string) => boolean); }, "zIndex" | ... 2 more ... | "shadow">> | undefined; onRest?(ds: Partial<...>): void; }>>): void', gave the following error.
    Value of type 'SpringsHandler<SpringValues>' has no properties in common with type 'Partial<Merge<{ zIndex: number; y: number; scale: number; shadow: number; immediate: boolean | ((v: string) => boolean); } & UseSpringBaseProps, { from?: Partial<Pick<{ zIndex: number; y: number; scale: number; shadow: number; immediate: boolean | ((v: string) => boolean); }, "zIndex" | ... 2 more ... | "shadow">> |...'. Did you mean to call it?
  Overload 2 of 2, '(i: number): Partial<Merge<{ zIndex: number; y: number; scale: number; shadow: number; immediate: boolean | ((v: string) => boolean); } & UseSpringBaseProps, { from?: Partial<Pick<{ zIndex: number; y: number; scale: number; shadow: number; immediate: boolean | ((v: string) => boolean); }, "zIndex" | ... 2 more ... | "shadow">> | undefined; onRest?(ds: Partial<...>): void; }>>', gave the following error.
    Argument of type 'SpringsHandler<SpringValues>' is not assignable to parameter of type 'number'.ts(2769)
useMySprings.tsx(33, 16): Did you mean to call this expression?

Can someone let me know what is possibly the problem here, I wrote the same code in JavaScript and it works fine.


Solution

  • Turnout this is a bug of react-spring, I updated the library to v9, and the error disappeared.