TypeScript does not infer type parameter correctly

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const useInfiniteMutations: <TData, TPage, TParams>(...: {
getNextPageParam?: (lastPageParam: TPage | undefined) => TPage | undefined;
mutationFn: (variables: { pageParam: TPage } & TParams) => Promise<TData>;
onSuccess?: (data: TData) => void;
}) => void
</code>
<code>const useInfiniteMutations: <TData, TPage, TParams>(...: { getNextPageParam?: (lastPageParam: TPage | undefined) => TPage | undefined; mutationFn: (variables: { pageParam: TPage } & TParams) => Promise<TData>; onSuccess?: (data: TData) => void; }) => void </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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;
},
});
</code>
<code>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; }, }); </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const useInfiniteMutations: <{
name: string;
pageParam: number;
}, number, MyVariables & {
pageParam: number;
}>
</code>
<code>const useInfiniteMutations: <{ name: string; pageParam: number; }, number, MyVariables & { pageParam: number; }> </code>
const useInfiniteMutations: <{
    name: string;
    pageParam: number;
}, number, MyVariables & {
    pageParam: number;
}>

which results the following error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const variables: MyVariables = {
name: "foo",
};
mutate(variables); // Property 'pageParam' is missing in type 'MyVariables' but required in type '{ pageParam: number; }'.typescript(2345)
</code>
<code>const variables: MyVariables = { name: "foo", }; mutate(variables); // Property 'pageParam' is missing in type 'MyVariables' but required in type '{ pageParam: number; }'.typescript(2345) </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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)
}
</code>
<code>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) } </code>
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)
}

2

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

  • such inference is easier as it doesn’t require dissecting an object type
  • it never gets the resulting parameter type “wrong” since intersections are essentially idempotent, so X & X & Y is equivalent to X & Y
  • it was needed to fix some incorrect inference behavior as reported in microsoft/TypeScript#8801
  • it is the supported way to work around the lack of inference from constraints, as described in microsoft/TypeScript#7234

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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;
}
</code>
<code>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; } </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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;
}
</code>
<code>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; } </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>mutate(variables); // okay
</code>
<code>mutate(variables); // okay </code>
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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,
};
};
</code>
<code>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, }; }; </code>
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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật