| How to Handle Optional Props in TypeScript :👈 | 👉:Discriminated Unions for React Component Props |
How to Avoid
|
How to Avoid any in React Applications (TypeScript)
1. What Is any in TypeScript?
In TypeScript, any is a type that disables type checking for a particular variable, property, or function.
When you use any, TypeScript allows you to perform almost any operation without checking whether it is valid.
let user: any = "John";
user = 100;
user = true;
user.doSomething(); // No TypeScript error
The problem is that TypeScript cannot protect you from invalid operations when you use any.
2. Why Should You Avoid any?
- Loss of type safety: TypeScript cannot identify many type-related mistakes.
- Runtime errors: Invalid values may reach your components.
- Poor IntelliSense: Editors cannot provide reliable suggestions.
- Difficult maintenance: Developers cannot easily understand expected data structures.
- Refactoring problems: Changes to data models may not reveal all affected locations.
3. Use Specific Types Instead of any
Define the expected data structure using type or interface.
const user: any = {
id: 1,
name: "John",
email: "john@example.com"
};
Better:
interface User {
id: number;
name: string;
email: string;
}
const user: User = {
id: 1,
name: "John",
email: "john@example.com"
};
Now TypeScript checks whether the object contains the required properties and correct value types.
4. Use unknown Instead of any
Use unknown when you receive a value whose type is not known.
Unlike any, unknown does not allow you to use the value until you check its type.
function displayValue(value: any) {
console.log(value.toUpperCase());
}
Better:
function displayValue(value: unknown) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}
The typeof check makes sure the value is a string before calling toUpperCase().
any | unknown |
|---|---|
| Disables type checking | Requires type checking |
| Allows operations without validation | Allows operations after narrowing |
| Can hide mistakes | Helps prevent unsafe operations |
| Avoid where possible | Preferred for genuinely unknown values |
5. Avoid any in React Props
Props define the data a parent component passes to a child component.
Use an interface or type to describe the expected props.
Avoid:function UserCard(props: any) {
return <h2>{props.name}</h2>;
}
Better:
interface UserCardProps {
name: string;
age: number;
}
function UserCard({ name, age }: UserCardProps) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
</div>
);
}
Now the component requires name and age with their correct types.
6. Avoid any in useState
Always define the state type when TypeScript cannot infer it correctly.
Avoid:const [user, setUser] = useState<any>(null);
Better:
interface User {
id: number;
name: string;
}
const [user, setUser] = useState<User | null>(null);
Here:
Userrepresents the expected user object.nullrepresents the initial state when no user is available.- TypeScript checks the value passed to
setUser.
setUser({
id: 1,
name: "John"
});
7. Avoid any in API Responses
API responses are a common source of any in React applications.
const response = await fetch("/api/users");
const users: any = await response.json();
Better:
interface User {
id: number;
name: string;
email: string;
}
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Failed to fetch users");
}
const users: User[] = await response.json();
This provides compile-time type checking for code that uses users.
response.json() does not automatically validate the actual API response. A TypeScript annotation does not guarantee that the server returned the expected structure.
For runtime validation, use a schema validation library such as Zod.
import { z } from "zod";
const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string()
});
type User = z.infer<typeof UserSchema>;
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Failed to fetch users");
}
const data: unknown = await response.json();
const user = UserSchema.parse(data);
Here, Zod checks the actual data at runtime and throws an error if the structure is invalid.
8. Avoid any in Event Handlers
React provides built-in event types. Use them instead of any.
function handleChange(event: any) {
console.log(event.target.value);
}
Better:
import { ChangeEvent } from "react";
function handleChange(
event: ChangeEvent<HTMLInputElement>
) {
console.log(event.target.value);
}
Other useful React event types:
| Event | TypeScript Type |
|---|---|
| Input change | ChangeEvent<HTMLInputElement> |
| Textarea change | ChangeEvent<HTMLTextAreaElement> |
| Select change | ChangeEvent<HTMLSelectElement> |
| Button click | MouseEvent<HTMLButtonElement> |
| Form submit | FormEvent<HTMLFormElement> |
| Keyboard event | KeyboardEvent<HTMLInputElement> |
You can also allow TypeScript to infer the event type when writing an inline handler.
<input
onChange={(event) => {
console.log(event.target.value);
}}
/>
9. Avoid any in Function Parameters and Return Types
Define the types of function parameters and return values.
Avoid:function calculateTotal(price: any, quantity: any): any {
return price * quantity;
}
Better:
function calculateTotal(
price: number,
quantity: number
): number {
return price * quantity;
}
This ensures that the function receives numbers and returns a number.
10. Avoid any in Arrays
Use specific array types.
Avoid:const users: any[] = [
{ id: 1, name: "John" },
{ id: 2, name: "David" }
];
Better:
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: "John" },
{ id: 2, name: "David" }
];
For arrays of primitive values:
const names: string[] = ["John", "David"];
const scores: number[] = [80, 90, 95];
const isActive: boolean[] = [true, false, true];
11. Avoid any in Context API
React Context is frequently used to share application data such as authentication details and user preferences.
Avoid:const AuthContext = createContext<any>(null);
Better:
import { createContext, useContext } from "react";
interface User {
id: number;
name: string;
}
interface AuthContextType {
user: User | null;
isAuthenticated: boolean;
logout: () => void;
}
const AuthContext = createContext<AuthContextType | undefined>(
undefined
);
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error(
"useAuth must be used inside AuthProvider"
);
}
return context;
}
This provides type safety when consuming authentication data.
12. Avoid any in Reusable Components
Generic types help create reusable components that support different data structures without using any.
function List({ items }: { items: any[] }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item.name}</li>
))}
</ul>
);
}
Better:
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
function List<T>({ items, renderItem }: ListProps<T>) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>
{renderItem(item)}
</li>
))}
</ul>
);
}
Usage:
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: "John" },
{ id: 2, name: "David" }
];
<List
items={users}
renderItem={(user) => <span>{user.name}</span>}
/>
The generic type T allows the component to work with different data structures while preserving type safety.
For production lists, use a stable unique key such as item.id rather than the array index when the item type provides one.
13. Use Union Types for Multiple Possible Values
Sometimes a variable can contain more than one type. Use a union type instead of any.
let status: any = "loading";
status = true;
status = 100;
Better:
type Status = "loading" | "success" | "error";
let status: Status = "loading";
status = "success";
Another example:
type UserId = string | number;
const userId: UserId = 101;
TypeScript now restricts the variable to the specified types.
14. Use Record for Dynamic Objects
When an object contains dynamic keys with a known value type, use Record.
const errors: any = {
name: "Name is required",
email: "Invalid email"
};
Better:
const errors: Record<string, string> = {
name: "Name is required",
email: "Invalid email"
};
For a fixed set of keys:
type FormField = "name" | "email";
const errors: Partial<Record<FormField, string>> = {
name: "Name is required"
};
Partial makes each specified property optional.
15. Configure TypeScript to Catch Unsafe Code
Use strict TypeScript compiler options to identify potential type-safety problems.
In tsconfig.json:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUncheckedIndexedAccess": true
}
}
What these options do:
| Option | Purpose |
|---|---|
strict | Enables a collection of strict type-checking options. |
noImplicitAny | Reports parameters and declarations that implicitly become any. |
strictNullChecks | Requires handling of null and undefined. |
noUncheckedIndexedAccess | Adds undefined to types for potentially missing indexed values. |
Note: strict: true already enables noImplicitAny and strictNullChecks. They are shown separately here to explain their purpose.
You can also use ESLint to identify explicit any usage:
// ESLint configuration example
{
rules: {
"@typescript-eslint/no-explicit-any": "error"
}
}
This helps prevent developers from introducing unnecessary any types.
16. Common Mistakes to Avoid
- Using
anyto fix TypeScript errors: Understand the error and correct the type instead. - Using
as any: Type assertions can bypass type checking and hide problems. - Using
anyfor API responses: Define response types and validate untrusted data at runtime. - Using
anyin Context: Define a proper context interface. - Using
any[]for every array: Specify the expected item type. - Overusing type assertions: Prefer type guards and proper type definitions.
- Confusing compile-time types with runtime validation: TypeScript types are removed during compilation.
17. Practical Migration Strategy for Existing React Applications
You do not need to remove every any from a large application in one day. Improve the application gradually.
- Enable
strictmode where practical. - Search the project for explicit
anydeclarations. - Start with shared interfaces and data models.
- Replace
anyin API responses with proper types and runtime validation where needed. - Fix component props and state types.
- Replace event-handler
anytypes with React event types. - Use generics for reusable components and Hooks.
- Add ESLint rules to prevent new unnecessary
anyusage. - Run TypeScript checks and tests after each change.
Useful command:
npx tsc --noEmit
This checks TypeScript errors without generating JavaScript output.
18. Quick Reference: What to Use Instead of any
| Situation | Avoid | Prefer |
|---|---|---|
| User object | any | User interface |
| Unknown data | any | unknown |
| React state | useState<any>() | useState<User | null>() |
| API response | any | Typed model + runtime validation |
| Event handler | event: any | React event types |
| Array | any[] | User[] |
| Multiple values | any | Union types |
| Dynamic object | any | Record<K, V> |
| Reusable component | any[] | Generics |
| Context API | createContext<any>() | Typed context |
19. Interview Questions and Answers
Q1. Why should we avoid any in React applications?
any disables TypeScript type checking for a value. It can hide errors, reduce IntelliSense support, and increase the possibility of runtime problems.
Q2. What is the difference between any and unknown?
any allows operations without type checking. unknown requires the developer to narrow or validate the type before using the value.
Q3. How do you type React component props?
Use an interface or type to define the expected properties and their data types.
Q4. How do you type API responses in React?
Define interfaces or types for the expected response and validate external data at runtime when reliability is important.
Q5. How do you avoid any in reusable components?
Use TypeScript generics so that components can work with different data types while preserving type safety.
Q6. What does noImplicitAny do?
It reports cases where TypeScript would otherwise infer an implicit any type.
Q7. Does TypeScript guarantee that API data is valid?
No. TypeScript checks types during development and compilation. It does not automatically validate data received from an API at runtime.
Q8. Is using any always wrong?
Not necessarily. It may be used temporarily when integrating with poorly typed legacy code or third-party libraries. However, it should be isolated and replaced with safer types whenever practical.
20. Key Takeaways
- Avoid using
anyas a shortcut to fix TypeScript errors. - Use interfaces and types for objects and component props.
- Use
unknownfor values whose types are not known. - Use union types when a variable supports multiple known types.
- Use generics to build reusable components.
- Use React's built-in event types for event handlers.
- Validate external API data at runtime when necessary.
- Enable strict TypeScript checks and ESLint rules.
Golden Rule: Use any only when there is a clear reason. Prefer specific types, unknown, union types, and generics to maintain a safe, predictable, and maintainable React application.
| How to Handle Optional Props in TypeScript :👈 | 👉:Discriminated Unions for React Component Props |
Comments and Discussion