alex
alex3y ago

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?
function useSessions(userId: number | null) {
trpc.sessions.useQuery({ userId }, { enabled: userId !== null });
...
}
function useSessions(userId: number | null) {
trpc.sessions.useQuery({ userId }, { enabled: userId !== null });
...
}
typescript: Type 'number | null' is not assignable to type 'number'.
12 Replies
TkDodo 🔮
TkDodo 🔮3y ago
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 🤔
Alex / KATT 🐱
One of the rare cases where I use !
function useSessions(userId: number | null) {
trpc.sessions.useQuery({ userId: userId! }, { enabled: userId });
...
}
function useSessions(userId: number | null) {
trpc.sessions.useQuery({ userId: userId! }, { enabled: userId });
...
}
or
function useSessions(userId: number | null) {
trpc.sessions.useQuery({ userId: userId as string }, { enabled: !!userId });
...
}
function useSessions(userId: number | null) {
trpc.sessions.useQuery({ userId: userId as string }, { enabled: !!userId });
...
}
alex
alexOP3y ago
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.
mark salsbery
mark salsbery3y ago
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
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
TkDodo 🔮
TkDodo 🔮3y ago
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 🙂
alex
alexOP3y ago
Ah I see, that makes sense. Thank you!
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
TkDodo 🔮
TkDodo 🔮3y ago
queryClient.refetchQueries does not bypass enabled: false, only refetch from useQuery does
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Alex / KATT 🐱
(hopefully) soon we can do conditional hooks and forget we ever had this problem
alex
alexOP3y ago
:o really? All the hoops we have to jump through just to make stuff work because of that rule :(

Did you find this page helpful?