React Type 'Element' not assignable to 'ReactNode' in Vite
When creating React apps with TypeScript in Vite, you might encounter the error Type 'Element' is not assignable to type 'ReactNode'
. This occurs in development environments like VS Code despite the app running correctly in the browser. Common causes include outdated or conflicting type definitions and misconfigured TS settings.
Solution 1: Update React Type Definitions
Most cases are resolved by updating React’s type definitions:
- Install the latest
@types/react
and@types/react-dom
:
npm install -D @types/react@latest @types/react-dom@latest
# or
yarn add -D @types/react@latest @types/react-dom@latest
- Ensure
package.json
lists these versions underdevDependencies
:
{
"devDependencies": {
"@types/react": "^18.2.x",
"@types/react-dom": "^18.2.x"
}
}
- If peer dependency conflicts arise:
npm install --legacy-peer-deps
Solution 2: Correct tsconfig.json Settings
Misconfigured TypeScript settings can trigger this error:
Include "dom" in compilerOptions.lib
:
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"moduleResolution": "Bundler", // Required for Vite
"jsx": "react-jsx"
}
}
- Key Fixes:
"lib": ["dom", ...]
ensures DOM types are recognized."moduleResolution": "Bundler"
aligns with Vite's resolver.
Solution 3: Clear VS Code Cache
VS Code’s cached TypeScript data may cause false positives:
- Open the command palette (
Ctrl/Cmd + Shift + P
). - Run
TypeScript: Restart TS Server
. - Alternatively, reload VS Code's window (
Ctrl/Cmd + Shift + P
>Developer: Reload Window
).
Solution 4: Reinstall Type Definitions
Inconsistent installations can corrupt types:
npm uninstall @types/react @types/react-dom
npm install -D @types/react @types/react-dom
Additional Checks
- Peer Dependencies: Ensure indirect dependencies like
@types/prop-types
are compatible (e.g., ≥15.7.8). - TypeScript Version: Verify compatibility between your TypeScript version and React types (e.g., TS 5.1.6+).
Why This Happens
TypeScript 5.1+ introduced stricter type checks for React nodes. Vite projects default to moduleResolution: "Bundler"
, which can conflict with outdated @types/react
definitions. Explicitly updating types and aligning TS configs resolves these mismatches.
Final Tip: After implementing fixes, restart your IDE and development server to ensure changes take effect.