query icon indicating copy to clipboard operation
query copied to clipboard

Overly restrictive typing for mutation callbacks (`onSuccess` etc) 2

Open Faithfinder opened this issue 3 years ago • 1 comments

Describe the bug

Right now types are defined as void | Promise<unknown>. This restricts returning and discarding values.

() => void type allows returning anything from the function, but void | whatever allows only "Nothing or whatever".

This means that a simple pattern of

 { onSuccess: () => toast("Message") }

Doesn't work if toast returns anything (usually the toast id for future manipulation).

Your minimal, reproducible example

https://www.typescriptlang.org/play?#code/C4TwDgpgBA8gdgZQK4GMUQM4YIxQLxQAUAlPgHxQBuA9gJYAmAUCtXBsFAGZJwrYBcsRKnRZcBEuSgBvRlCgAnCMCQK4UAOQAJCABtd1DYwC+jRqEhDkaTBgBM+IqTwUaDKAB8oABQXUAtrQYEAA8PADWcNQA7nBkzKzsXDwodoLw1qL2jpIuMnKKyqrq2noGRsZAA

react-query version

4.0.10

TypeScript version

4.7.3

Additional context

The problem is minor and easily enough bypassed by either marking the callback as async or avoiding the shorthand syntax that returns implicitly.

Still, I think making the return type unknown entirely would be better ergonomics.

Also, found a similar issue here: https://github.com/TanStack/query/issues/2166

Faithfinder avatar Aug 04 '22 18:08 Faithfinder

I agree making the return type unknown would be better, I could get to work on it.

nick-0101 avatar Aug 07 '22 00:08 nick-0101

so Promise<unknown> | unknown would be the proposed type?

TkDodo avatar Aug 12 '22 14:08 TkDodo

Sure, though that's technically no different than just unknown.

Honestly, it feels like a Typescript bug, but I'm not ready to champion a cause with Typescript. And they might think it's a feature.

Faithfinder avatar Aug 12 '22 14:08 Faithfinder

yeah let's still just go for Promise<unknown> | unknown please :)

TkDodo avatar Aug 12 '22 18:08 TkDodo