useMutation's onSuccess result type falls back to `unknown` when mutationFn is a curried/higher-order function #10156
Send to my agentDescribe the bug#
When passing a curried (higher-order) function directly as mutationFn inside the useMutation options object, TypeScript correctly infers the TData and TVariables types — until you add an onSuccess or onSettled callback. At that point, the data/result parameter in onSuccess falls back to unknown, and TVariables also degrades.
This appears to be a TypeScript co-dependent generic inference issue: when all properties are provided in a single object literal, TypeScript tries to infer all type parameters (TData, TError, TVariables, TContext) simultaneously. The onSuccess(result) callback creates a circular dependency — TS needs TData to type result, but inferring TData from a complex curried mutationFn return type is disrupted by the additional constraint, causing fallback to unknown.
Your minimal, reproducible example#
https://tanstack.com/query/latest/docs/framework/react/examples/simple
Steps to reproduce#
import { useMutation } from "@tanstack/react-query";
// ---- Minimal type setup ----
interface ResponseWrapper<T> {
info: T;
success: boolean;
}
type DataResult<T, E> =
| { data: T; error: null }
| { data: null; error: E & { status: number } };
interface APIEndpoints {
"/users/login": {
method: "POST";
response: ResponseWrapper<{ id: string; token: string }>;
body: { email: string; password: string };
};
}
type ExtractField<Rule, Key extends string> = Key extends "response"
? Rule extends { response: infer T } ? T : never
: Key extends "body"
? Rule extends { body: infer B } ? B : undefined
: never;
// ---- Curried mutate function (simulating a typed fetch client) ----
function mutate<
Path extends keyof APIEndpoints,
Rule = APIEndpoints[Path],
B = ExtractField<Rule, "body">,
T = ExtractField<Rule, "response">,
>(path: Path, options?: { authenticate?: boolean }) {
return async (variables?: NonNullable<B>): Promise<DataResult<T, { message: string }>> => {
const res = await fetch(path, {
method: "POST",
body: JSON.stringify(variables),
});
const data = await res.json();
return { data, error: null };
};
}
// ---- Reproduction ----
// ✅ Works — TData and TVariables are correctly inferred
const mutation1 = useMutation({
mutationFn: mutate("/users/login", { authenticate: true }),
});
// Hovering mutation1: UseMutationResult<DataResult<ResponseWrapper<{id: string; token: string}>, ...>, Error, {email: string; password: string}, unknown>
// ❌ Broken — adding onSuccess causes result to become `unknown`
const mutation2 = useMutation({
mutationFn: mutate("/users/login", { authenticate: true }),
onSuccess(result) {
// ^? unknown — should be DataResult<ResponseWrapper<...>, ...>
console.log(result);
},
});
// Hovering mutation2: UseMutationResult<unknown, Error, unknown, unknown>
// ⚠️ Partial workaround — TData is inferred, but TVariables degrades to `any`
const mutation3 = useMutation({
mutationFn: (v: any) => mutate("/users/login", { authenticate: true })(v),
onSuccess(result) {
// result is correctly typed here, but TVariables is `any`
},
});
// Hovering mutation3: UseMutationResult<DataResult<...>, Error, any, unknown>
Expected behavior#
onSuccess(result) should have result typed as the resolved return type of mutationFn, regardless of whether mutationFn is a direct function or a curried/higher-order function. Adding onSuccess should not degrade type inference.
// ✅ Workaround — extract mutationFn to a separate variable
const mutationFn = mutate("/users/login", { authenticate: true });
const mutation = useMutation({
mutationFn,
onSuccess(result) {
// result is correctly typed as DataResult<ResponseWrapper<...>, ...>
},
});
This works because TypeScript resolves mutationFn's type at the assignment site (including its full return type), so by the time useMutation sees it, the type is already concrete — no co-inference conflict with onSuccess.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
All Platforms
Tanstack Query adapter#
react-query
TanStack Query version#
5.90.21
TypeScript version#
5.9.3
Additional context#
This is likely a TypeScript limitation with simultaneous generic inference from multiple object literal properties. When all properties are inlined:
- TS sees
mutationFn→ tries to inferTDataandTVariablesfrom its signature - TS sees
onSuccess(result)→ needsTDatato typeresult - The competing inference sites cause TS to bail out and default to
unknown
When the function is pre-assigned to a variable, step 1 is resolved independently, so step 2 has a concrete type to work with.
This pattern affects any library that relies on inferring complex generic types from object literals with interdependent callback properties — not just useMutation, but potentially useQuery with select, and similar APIs.
TkDodo closed this
TkDodo added labelstypes
TkDodo added labelsinvalid
TkDodo added labelsworks as designed
Sign in to join this conversation.
this has nothing to do with curried functions or mutate for that matter. Here is your example simplified that just works:
https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgVwM4FMCyyYEMbAQB2cAvnAGZQQhwBEAAnkangMYDWA9FOrmzAC0AR2TooATzoBuAFCyuXOIJWC4mYEVC4ANnBgSw6OBhjIwy1fIrIiAwiRA586ABRh8ACwBcJmFE0AcwBKRFk4OF4zKBJcVAk7OFcAN1wA3AAjHXRUXyJkEAzxYN8ABWoQYAwAHiQQHNRcQPRfVgCiQLIAPjgAXh6EcIjI9GiScpoq9AA6XlQIHWS3OoamlrgAZX8g9y84AGo4VPSsnODSYKHSOVJ5RUsVOAAldDBqABNke2IHwTulQCg5HAAOrQDioOCAFAI4AAVAAi+FwcFwRHesIAamlgJlshC0sY2NBeAIdBI4JoKOJeO9ZISWPAnHgCMQAIx9FAYbBMhyuQYRRn4BwAMSIvgFMDcdC4aHEqC4OgggU0dGCABpZBc5PcABIQJbtTrihws3wAVU5zmZRBeqGQOhg1QReBtdodNsgLHQwKguDARigtWA71a2w60n0EA46FFfgNpC6qrg02TCbgAFEoNQoImEOgQLhgDoQwbwx5UKgAO7QYOxoKkRO2DhECAVohdf5wQAy5HAAELUKMkaG4d7vIJwYgbL5sBpwNi4GUQuauiNwIqE+pwAAGjebrc3tOIrDgRuIACZ2TKuYLiLyhieiCKxZbJdKMFA5QqlUQVeqIhOpw0rhLvaoR8sM9zDMMAB6AD8QwRHS8zZNMn5ATkrrBHIET1hqmFAA
the problem is somewhere in your generic api endpoints extraction. I threw AI at the problem and came to a working solution, not sure if it’s any good.
The main problem seems to be around
variablesneeding to be always defined while they are optional in your example.