Type safety with enabled option
https://tkdodo.eu/blog/react-query-and-type-script#type-safety-with-the-enabled-option
What is the best way to solve this with trpc?
typescript: Type 'number | null' is not assignable to type 'number'.
12 Replies
Good question, I also thought about this. Possibly the router in the backend will need to accept null as input? But that doesn't look too sexy. Curious what others can suggest 🤔
One of the rare cases where I use
!
or
That's also one thought I had, but couldn't bring myself to implement it, just felt too wrong :D
Fair enough, going to use that for now, thanks!
I'm not a typescript wizard yet but would it - just theoretically - be possible to infer that
userId
is not null from the enabled
option?
I guess that would be on the react-query side then, not on trpc.I don't think it feels wrong. The parameter is typed so one has to do what it takes to coerce or calculate a boolean based on that parameters type and value. TS helps by making sure you catch all type-related cases. Also, be mindful of implementation if 0 is a valid user ID, just saying... hehe
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
not if enabled is
type boolean
and that changes at runtime. Like !!userId
is not something that can be evaluated at compile time.
also, even if possible, it would be wrong, because enabled
can be bypassed by calling refetch()
returned from useQuery
. So TypeScript is correct - it is potentially undefined 🙂Ah I see, that makes sense. Thank you!
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
queryClient.refetchQueries does not bypass
enabled: false
, only refetch
from useQuery
doesUnknown User•3y ago
Message Not Public
Sign In & Join Server To View
(hopefully) soon we can do conditional hooks and forget we ever had this problem
:o really?
All the hoops we have to jump through just to make stuff work because of that rule :(