T
TanStack3y ago
optimistic-gold

TS errors when you use search params to conditionally render in the "root" of a component

If I do something like
function BrokenApp() {
const { shouldRenderApp } = useSearch({ from: brokenAppRoute.id });

return <>{shouldRenderApp && <div>My beautiful app</div>}</>;
// or return shouldRenderApp && <div>My beautiful app</div>;
}
function BrokenApp() {
const { shouldRenderApp } = useSearch({ from: brokenAppRoute.id });

return <>{shouldRenderApp && <div>My beautiful app</div>}</>;
// or return shouldRenderApp && <div>My beautiful app</div>;
}
TS says
'shouldRenderApp' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.(7022)
'shouldRenderApp' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.(7022)
but if I wrap return into non-fragment (like div), it works. Link to repro stackblitz: https://stackblitz.com/edit/vitejs-vite-4atklj?file=src%2Fmain.tsx
No description
4 Replies
optimistic-gold
optimistic-goldOP3y ago
https://stackblitz.com/edit/vitejs-vite-yburzq still repeats in the latest version
rising-crimson
rising-crimson3y ago
I found a fix for this! You can set the return type of the function to ReactNode.
import { ReactNode } from "react";

function BrokenApp(): ReactNode {
...
}
import { ReactNode } from "react";

function BrokenApp(): ReactNode {
...
}
plain-purple
plain-purple3y ago
Wow that fixed it, thank you! TS can be so weird sometimes... I think this should be filed as a bug, since conditional rendering with search params is a pretty common pattern. @la.sintez did you file a GitHub issue?
optimistic-gold
optimistic-goldOP3y ago
Nope. Thanks for a heads-up though.

Did you find this page helpful?