| Discriminated Unions for React Component Props :👈 | 👉:How to Structure a React Project |
Common TypeScript Errors in React and How to Fix Them |
Common TypeScript Errors in React and How to Fix Them
1. Introduction
TypeScript helps React developers identify errors during development by checking data types, component props, function parameters, state values and other parts of an application.
However, when working with React and TypeScript, developers frequently encounter errors related to incorrect types, missing properties, null values, event handlers, API responses and Hooks.
This guide covers common TypeScript errors in React, why they occur, and how to fix them with practical examples.
2. Type 'X' Is Not Assignable to Type 'Y'
Error:
Type 'string' is not assignable to type 'number'.
Why does this happen?
This error occurs when you assign a value of one type to a variable that expects another type.
Incorrect code:let age: number = 25;
age = "Twenty Five";
Here, age expects a number, but a string is assigned to it.
let age: number = 25;
age = 30;
If the variable legitimately supports multiple types, use a union type.
let userId: string | number;
userId = 101;
userId = "USER101";
3. Property Does Not Exist on Type
Error:
Property 'name' does not exist on type '{}'.
Why does this happen?
TypeScript cannot identify a property because the object has not been given the correct type.
Incorrect code:const [user, setUser] = useState({});
return <h2>{user.name}</h2>;
The initial state is inferred as an empty object type.
Solution:interface User {
id: number;
name: string;
}
const [user, setUser] = useState<User>({
id: 1,
name: "John"
});
return <h2>{user.name}</h2>;
Define an interface that describes the object structure.
4. Object Is Possibly 'Null'
Error:
Object is possibly 'null'.
Why does this happen?
This error occurs when a variable can contain null, but you try to access its properties without checking whether it contains an object.
interface User {
id: number;
name: string;
}
const [user, setUser] = useState<User | null>(null);
return <h2>{user.name}</h2>;
The initial state is null, so TypeScript cannot guarantee that user.name is safe.
return (
<div>
{user ? (
<h2>{user.name}</h2>
) : (
<p>User not available</p>
)}
</div>
);
Solution 2: Optional chaining
return <h2>{user?.name}</h2>;
Optional chaining returns undefined when user is null or undefined instead of accessing the property.
5. Type 'undefined' Is Not Assignable to Type
Error:
Type 'undefined' is not assignable to type 'string'.
Why does this happen?
A property or function may return undefined, but the destination expects a string.
interface User {
name?: string;
}
const user: User = {};
const userName: string = user.name;
Because name is optional, it may be undefined.
const userName: string = user.name ?? "Guest";
Solution 2: Check before using
if (user.name !== undefined) {
const userName: string = user.name;
}
6. No Overload Matches This Call
Error:
No overload matches this call.
Why does this happen?
This error occurs when a function or React Hook receives arguments that do not match any of its supported signatures.
Incorrect code:const [count, setCount] = useState<number>(null);
The state expects a number, but the initial value is null.
Solution:const [count, setCount] = useState<number | null>(null);
Now the state explicitly allows both number and null values.
7. Type 'X' Is Not Assignable to Type 'ReactNode'
Error:
Type 'object' is not assignable to type 'ReactNode'.
Why does this happen?
React cannot directly render an ordinary JavaScript object as a child.
Incorrect code:const user = {
id: 1,
name: "John"
};
return <div>{user}</div>;
Solution:
Render a property or use JSON serialization when displaying an object for debugging.
return <div>{user.name}</div>;
// For debugging:
return <pre>{JSON.stringify(user, null, 2)}</pre>;
8. Property 'map' Does Not Exist on Type
Error:
Property 'map' does not exist on type '{}'.
Why does this happen?
The variable is not typed as an array, or its inferred type does not support the map() method.
const [users, setUsers] = useState({});
return (
<ul>
{users.map(user => (
<li>{user.name}</li>
))}
</ul>
);
Solution:
interface User {
id: number;
name: string;
}
const [users, setUsers] = useState<User[]>([]);
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
Use User[] to define an array of users.
9. Type 'string' Is Not Assignable to Type 'SetStateAction'
Error:
Argument of type 'string' is not assignable to
parameter of type 'SetStateAction<number>'.
Why does this happen?
The value passed to a state setter does not match the state type.
Incorrect code:const [count, setCount] = useState<number>(0);
setCount("10");
Solution 1: Convert the value to a number
setCount(Number("10"));
Solution 2: Use a string state if the value represents text
const [count, setCount] = useState<string>("0");
setCount("10");
Choose the state type according to how the value is used in your application.
10. Event Parameter Implicitly Has an 'any' Type
Error:
Parameter 'event' implicitly has an 'any' type.
Why does this happen?
TypeScript cannot determine the event parameter type in some function declarations.
Incorrect code:function handleChange(event) {
console.log(event.target.value);
}
Solution:
import { ChangeEvent } from "react";
function handleChange(
event: ChangeEvent<HTMLInputElement>
) {
console.log(event.target.value);
}
For a button click:
import { MouseEvent } from "react";
function handleClick(
event: MouseEvent<HTMLButtonElement>
) {
console.log(event.currentTarget);
}
You can also let TypeScript infer the event type in JSX:
<input
onChange={(event) => {
console.log(event.target.value);
}}
/>
11. Type 'null' Is Not Assignable to Type 'HTMLInputElement'
Error:
Type 'null' is not assignable to type 'HTMLInputElement'.
Why does this happen?
A React ref may not point to an HTML element initially because the element has not yet been mounted.
Incorrect code:const inputRef = useRef<HTMLInputElement>(null);
Solution:
const inputRef = useRef<HTMLInputElement | null>(null);
return (
<input ref={inputRef} />
);
When accessing the element, check whether the ref contains a value.
function focusInput() {
inputRef.current?.focus();
}
12. Type 'X' Is Not Assignable to Component Props
Error:
Property 'age' does not exist on type 'UserProps'.
Why does this happen?
The parent component passes a property that is not defined in the child component's props interface.
Incorrect code:interface UserProps {
name: string;
}
function UserCard({ name }: UserProps) {
return <h2>{name}</h2>;
}
// Parent component
<UserCard name="John" age={25} />
Solution:
interface UserProps {
name: string;
age: number;
}
function UserCard({ name, age }: UserProps) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
</div>
);
}
Alternatively, remove the unnecessary age property from the parent if the child does not need it.
13. Type '() => void' Is Not Assignable to Type 'MouseEventHandler'
Why does this happen?
A callback may have been defined with an incompatible parameter or return type, or the event handler may have been invoked instead of passed as a function.
Incorrect code:function handleClick(event: string) {
console.log(event);
}
<button onClick={handleClick}>
Click Me
</button>
The button expects a React mouse event handler, but the function expects a string.
Solution:import { MouseEventHandler } from "react";
const handleClick: MouseEventHandler<HTMLButtonElement> = (
event
) => {
console.log(event.currentTarget);
};
<button onClick={handleClick}>
Click Me
</button>
If the handler does not need the event, it can simply be:
function handleClick() {
console.log("Button clicked");
}
<button onClick={handleClick}>
Click Me
</button>
14. Type 'Promise<void>' Is Not Assignable to Type 'EffectCallback'
Error:
Argument of type '() => Promise<void>' is not assignable
to parameter of type 'EffectCallback'.
Why does this happen?
The callback passed to useEffect must return either nothing or a cleanup function. An async function returns a Promise, which is not a valid effect cleanup return value.
useEffect(async () => {
const response = await fetch("/api/users");
const data = await response.json();
setUsers(data);
}, []);
Solution:
useEffect(() => {
async function fetchUsers() {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Failed to fetch users");
}
const data: User[] = await response.json();
setUsers(data);
}
fetchUsers().catch(console.error);
}, []);
For production code, also handle loading and error states and clean up requests when appropriate, for example with AbortController.
15. Type 'never' Appears Unexpectedly
Error example:
Property 'name' does not exist on type 'never'.
Why does this happen?
This can happen when TypeScript determines that a value has no possible valid type in a particular code path. A common cause is an empty array being inferred too narrowly or incorrect union narrowing.
Incorrect code:const [users, setUsers] = useState([]);
setUsers([
{ id: 1, name: "John" }
]);
users.map(user => user.name);
Solution:
interface User {
id: number;
name: string;
}
const [users, setUsers] = useState<User[]>([]);
setUsers([
{ id: 1, name: "John" }
]);
users.map(user => user.name);
Explicitly define the array element type when TypeScript cannot infer it correctly.
16. Type 'unknown' Is Not Assignable to Type
Error:
Type 'unknown' is not assignable to type 'string'.
Why does this happen?
The unknown type requires validation before assigning its value to a more specific type.
function getName(value: unknown) {
const name: string = value;
}
Solution:
function getName(value: unknown) {
if (typeof value === "string") {
const name: string = value;
return name;
}
return "Unknown";
}
Use type guards to narrow the value before using it.
17. Cannot Find Module or Its Corresponding Type Declarations
Error:
Cannot find module 'some-library' or its corresponding
type declarations.
Why does this happen?
- The package is not installed.
- The import path is incorrect.
- The package does not provide TypeScript declarations.
- The TypeScript module resolution configuration is incorrect.
First, install the package if it is missing.
npm install some-library
If the library requires separate type declarations and they are available, install them:
npm install --save-dev @types/some-library
Also verify the import path and the package's TypeScript documentation. Not every package has a separate @types package.
18. Cannot Find Name 'React'
Error:
Cannot find namespace 'React'.
Why does this happen?
This can occur when React types are missing, or when a React namespace type is used without the appropriate type declarations.
Solution:Make sure React and its type declarations are installed:
npm install react react-dom
npm install --save-dev @types/react @types/react-dom
Alternatively, import the specific types you need:
import type { ReactNode } from "react";
interface CardProps {
children: ReactNode;
}
19. Incorrectly Using Type Assertions
Problem:
Type assertions tell TypeScript to treat a value as a particular type. They do not validate the value at runtime.
Risky code:const user = responseData as User;
This may hide an incorrect API response structure.
Better approach:const data: unknown = responseData;
if (
typeof data === "object" &&
data !== null &&
"name" in data &&
typeof data.name === "string"
) {
console.log(data.name);
}
For complex API responses, use a runtime schema validator such as Zod instead of relying on type assertions.
20. Quick Reference: Common Errors and Fixes
| TypeScript Error | Common Cause | Typical Fix |
|---|---|---|
| Type is not assignable | Incorrect value type | Use the correct type or a union |
| Property does not exist | Incorrect object type | Define an interface |
| Object is possibly null | Nullable value not checked | Use conditional checks or optional chaining |
| Undefined is not assignable | Optional property | Use a default value or narrow the type |
| No overload matches | Incorrect function arguments | Match the expected function signature |
| Object is not ReactNode | Rendering an object directly | Render a property or serialize it |
| Map does not exist | Value is not typed as an array | Define an array type |
| Implicit any | Missing parameter type | Add an explicit type |
| Null not assignable to ref | Incorrect ref type | Use useRef<Element | null> |
| Promise not assignable to EffectCallback | Async effect callback | Use an inner async function |
| Property does not exist on never | Incorrect inference or narrowing | Define the correct type |
| Unknown not assignable | Value not narrowed | Use type guards |
| Cannot find module | Missing package or declarations | Install or correct the import |
21. Best Practices to Prevent TypeScript Errors
- Define interfaces and types: Create clear data models for API responses, component props and application state.
- Avoid unnecessary any: Prefer specific types,
unknown, union types and generics. - Use strict mode: Enable strict TypeScript checking in
tsconfig.json. - Handle null and undefined: Use appropriate checks, optional chaining and default values.
- Type React Hooks: Explicitly define state and ref types when inference is insufficient.
- Use React event types: Avoid untyped event parameters.
- Validate API responses: TypeScript types alone do not validate external data at runtime.
- Avoid unnecessary type assertions: Use type guards to establish that values have the expected shape.
- Run TypeScript checks: Include type checking in your development and build process.
22. Useful TypeScript Commands
Check TypeScript errors without generating JavaScript:
npx tsc --noEmit
Install React TypeScript declarations:
npm install --save-dev @types/react @types/react-dom
Start a Vite React application with TypeScript:
npm create vite@latest my-react-app -- --template react-ts
23. Interview Questions and Answers
Q1. Why do TypeScript errors occur in React?
They occur when component props, state values, function parameters, event handlers or other expressions do not match their declared types.
Q2. How do you fix an object possibly null error?
Check whether the object exists before accessing its properties. Conditional rendering and optional chaining are common solutions.
Q3. How do you fix an implicit any error?
Define the correct parameter type or allow TypeScript to infer the type from a properly typed context.
Q4. Why should we use User[] instead of any[]?
User[] ensures that each array item follows the User structure, providing better type checking and IntelliSense.
Q5. Why should an async function not be passed directly to useEffect?
An async function returns a Promise, whereas useEffect expects its callback to return nothing or a cleanup function.
Q6. How do you type a React ref?
Use useRef<HTMLInputElement | null>(null) when referencing an input element.
Q7. What is the difference between a type error and a runtime error?
A type error is identified by TypeScript during static checking. A runtime error occurs while the application is executing.
Q8. Does fixing TypeScript errors guarantee that the React application has no bugs?
No. TypeScript catches many type-related problems, but it cannot prevent every logical error, API failure or runtime issue.
24. Key Takeaways
- Most React TypeScript errors are related to incorrect types, missing properties, null values and incompatible function arguments.
- Define interfaces for objects and component props.
- Use explicit state and ref types when necessary.
- Handle nullable and optional values safely.
- Use the correct React event types.
- Do not pass async functions directly to
useEffect. - Use type guards instead of unsafe type assertions.
- Run
npx tsc --noEmitregularly to identify type errors.
Golden Rule: Do not fix TypeScript errors by blindly using any or type assertions. Understand why the error occurs, define the correct type, and make the component type-safe.
| Discriminated Unions for React Component Props :👈 | 👉:How to Structure a React Project |
Comments and Discussion