typescripttypescript-generics

TypeScript does not infer type parameter correctly


In index.tsx in this backbone example, I have a function:

const useInfiniteMutations: <TData, TPage, TParams>(...: {
  getNextPageParam?: (lastPageParam: TPage | undefined) => TPage | undefined;
  mutationFn: (variables: { pageParam: TPage } & TParams) => Promise<TData>;
  onSuccess?: (data: TData) => void;
}) => void

And when I pass arguments to the parameters:

type MyVariables = {
  name: string;
};

const { mutate } = useInfiniteMutations({
  getNextPageParam: (lastPageParam = -1) => lastPageParam + 1,
  mutationFn: async ({
    name,
    pageParam,
  }: MyVariables & { pageParam: number }) => {
    const result = { name, pageParam };
    return result;
  },
});

and I found this weird type inference:

const useInfiniteMutations: <{
    name: string;
    pageParam: number;
}, number, MyVariables & {
    pageParam: number;
}>

which results the following error:

const variables: MyVariables = {
  name: "foo",
};

mutate(variables); // Property 'pageParam' is missing in type 'MyVariables' but required in type '{ pageParam: number; }'.typescript(2345)

Why TParams is not inferred as MyVariables? How can I make it?

I researched a lot and tried a lot of approaches that I've learned so far, but none of them worked...

This is the full minimal reproducible example:

import { useEffect, useState } from "react";

export const useInfiniteMutations = <TData, TPage, TParams>({
  getNextPageParam,
  mutationFn,
  onSuccess,
}: {
  getNextPageParam?: (lastPageParam: TPage | undefined) => TPage | undefined;
  mutationFn: (variables: { pageParam: TPage } & TParams) => Promise<TData>;
  onSuccess?: (data: TData) => void;
}) => {
  const [params, setParams] = useState<TParams>();

  const [nextPageParam, setNextPageParam] = useState<TPage>();

  const mutate = (newParams: TParams) => {
    const newNextPageParam = getNextPageParam?.(undefined);
    if (newNextPageParam === undefined) {
      return;
    }

    setNextPageParam(newNextPageParam);
    setParams(newParams);
  };

  useEffect(() => {
    if (params === undefined || nextPageParam === undefined) {
      return;
    }

    mutationFn({
      ...params,
      pageParam: nextPageParam,
    }).then((data) => {
      onSuccess?.(data);
    });
  }, [nextPageParam]);

  return {
    mutate,
  };
};

export function demo() {
  type MyVariables = {
    name: string;
  };

  const { mutate } = useInfiniteMutations({
    getNextPageParam: (lastPageParam = -1) => lastPageParam + 1,
    mutationFn: async ({
      name,
      pageParam,
    }: MyVariables & { pageParam: number }) => {
      const result = { name, pageParam };

      return result;
    },
  });

  const variables: MyVariables = {
    name: "foo",
  };

  mutate(variables); // Property 'pageParam' is missing in type 'MyVariables' but required in type '{ pageParam: number; }'.typescript(2345)
}


Solution

  • TypeScript doesn't generally perform surgery on intersection types when inferring generic type arguments. If you have a generic function parameter whose type is T & Y (where T is a generic type parameter) and you pass in an argument of type Z which is equivalent to X & Y, TypeScript is very likely to infer T to be the entire type Z and not just X.

    That's because

    So it's unlikely that you can "make" TypeScript infer the type you wanted for TParams in your example. In situations like this, it's more useful to just allow TypeScript to infer the type the way it does, and then you can explicitly de-intersect it yourself using something like the Omit<T, K> utility type.


    So your current function looks like this:

    declare const useInfiniteMutations:
        <TData, TPage, TParams>({ getNextPageParam, mutationFn, onSuccess }: {
            getNextPageParam?: (lastPageParam: TPage | undefined) => TPage | undefined;
            mutationFn: (variables: { pageParam: TPage } & TParams) => Promise<TData>;
            onSuccess?: (data: TData) => void;
        }) => {
            mutate: (newParams: TParams) => void;
        }
       
    

    But we need to change it to the following:

    declare const useInfiniteMutations:
        <TData, TPage, TParams>({ getNextPageParam, mutationFn, onSuccess }: {
            getNextPageParam?: (lastPageParam: TPage | undefined) => TPage | undefined;
            mutationFn: (variables: { pageParam: TPage } & TParams) => Promise<TData>;
            onSuccess?: (data: TData) => void;
        }) => {
            mutate: (newParams: Omit<TParams, "pageParam">) => void;
        }
       
    

    See how the newParams parameter of mutate is of type Omit<TParams, "pageParam">, so even if TypeScript infers a type with a pageParam property for TParams, the mutate function won't need that property. So your call with work:

    mutate(variables); // okay
    

    As for the implementation of useInfiniteMutations, you'll need to change some occurrences of TParams to Omit<TParams, "pageParam">, and then anywhere you were relying on TParams & {pageParam: TPage} to be equivalent to Omit<TParams, "pageParam"> & {pageParam: TPage}, you'll need to use a type assertion, because TypeScript can't see higher order generic type equivalences like that. See microsoft/TypeScript#28884 for more information.

    So your implementation might look like

    export const useInfiniteMutations = <TData, TPage, TParams>({
        getNextPageParam,
        mutationFn,
        onSuccess,
    }: {
        getNextPageParam?: (lastPageParam: TPage | undefined) => TPage | undefined;
        mutationFn: (variables: { pageParam: TPage } & TParams) => Promise<TData>;
        onSuccess?: (data: TData) => void;
    }) => {
        const [params, setParams] = useState<Omit<TParams, "pageParam">>();
    
        const [nextPageParam, setNextPageParam] = useState<TPage>();
    
        const mutate = (newParams: Omit<TParams, "pageParam">) => {
            const newNextPageParam = getNextPageParam?.(undefined);
            if (newNextPageParam === undefined) {
                return;
            }
    
            setNextPageParam(newNextPageParam);
            setParams(newParams);
        };
    
        useEffect(() => {
            if (params === undefined || nextPageParam === undefined) {
                return;
            }
    
            mutationFn({
                ...params as TParams, // <-- this is a white lie
                pageParam: nextPageParam,
            }).then((data) => {
                onSuccess?.(data);
            });
        }, [nextPageParam]);
    
        return {
            mutate,
        };
    };
    

    where the params as TParams is needed to convince TypeScript that the resulting object is of the expected type.

    Playground link to code