As React applications become larger and more complex, managing data correctly becomes increasingly important.
Consider the following JavaScript example:
let age = 21;
age = "Hello";
JavaScript allows this because it is dynamically typed, but changing a variable from a number to a string can introduce unexpected bugs.
Type Safety helps prevent these problems by ensuring data has the correct type before or while the application runs.
Popular tools used for type safety include:
Note: Throughout this course, we will primarily focus on TypeScript and Zod, as they are commonly used together in modern React applications.
Type Safety ensures that variables, functions, and objects always contain the expected type of data.
Common data types include:
By enforcing types, developers can detect many mistakes before an application reaches production.
Type safety provides many advantages:
Large applications become much easier to maintain when every piece of data has a clearly defined type.
TypeScript is a superset of JavaScript developed by Microsoft.
Unlike JavaScript, TypeScript adds static type checking, helping developers catch errors during development.
A superset includes everything available in JavaScript along with additional features.
JavaScript
│
▼
TypeScript
Every valid JavaScript program is also valid TypeScript.
TypeScript simply adds extra capabilities such as type checking.
npm install typescript
let name: string =
"Samir";
let age: number =
21;
let isAdmin: boolean =
true;
let age: number =
21;
age = "Hello";
TypeScript reports an error:
Type 'string'
is not assignable
to type 'number'
This error is detected before the application runs, preventing many runtime bugs.
const numbers:
number[] = [1, 2, 3];
The array can contain only numbers.
const user: {
name: string;
age: number;
} = {
name: "Samir",
age: 21
};
Every property must match its declared type.
Interfaces define the structure of objects.
interface User {
name: string;
age: number;
}
Usage:
const user: User = {
name: "Samir",
age: 21
};
Interfaces make object definitions reusable across an application.
Function parameters and return values can also have types.
function add(
a: number,
b: number
): number {
return a + b;
}
This function accepts two numbers and always returns a number.
TypeScript is commonly used to define React component props.
interface UserProps {
name: string;
}
function User({
name
}: UserProps) {
return (
<h1>
{name}
</h1>
);
}
If the required prop is missing or has the wrong type, TypeScript reports an error.
TypeScript helps React developers by:
It is now the standard choice for many React projects.
Modern React applications commonly use:
React
+
TypeScript
TypeScript source files use the following extensions:
.ts
.tsx
.ts → TypeScript files.tsx → TypeScript files containing JSXTypeScript
│
▼
Compiler
│
▼
JavaScript
│
▼
Browser
The browser only understands JavaScript.
TypeScript is compiled into JavaScript before execution.
Zod is a TypeScript-first schema validation library.
While TypeScript checks types during development, it cannot verify external data at runtime.
For example:
may still contain invalid values.
Zod validates this data while the application is running.
npm install zod
import { z }
from "zod";
const UserSchema =
z.object({
name:
z.string(),
age:
z.number()
});
A schema defines the expected structure of data.
UserSchema.parse({
name: "Samir",
age: 21
});
This passes validation successfully.
UserSchema.parse({
name: "Samir",
age: "21"
});
Since "21" is a string instead of a number, Zod throws a validation error.
z.string()
z.number()
z.boolean()
z.string().email()
z.string().min(6)
z.string().max(20)
const LoginSchema =
z.object({
email:
z.string()
.email(),
password:
z.string()
.min(6)
});
This schema requires:
LoginSchema.parse({
email:
"test@gmail.com",
password:
"123456"
});
If the data matches the schema, validation succeeds.
Instead of throwing an error, safeParse() returns a result object.
const result =
LoginSchema.safeParse(
data
);
Check whether validation succeeded:
if (result.success) {
console.log(
result.data
);
}
This approach is commonly used in production applications.
One of the most common modern React stacks combines:
React Hook Form
+
Zod
npm install zod @hookform/resolvers
const schema =
z.object({
email:
z.string()
.email(),
password:
z.string()
.min(6)
});
const form =
useForm({
resolver:
zodResolver(
schema
)
});
The resolver automatically validates form data using the Zod schema.
Combining React Hook Form with Zod provides:
| Feature | TypeScript | Zod |
|---|---|---|
| Compile-Time Checking | Yes | No |
| Runtime Validation | No | Yes |
| Type Checking | Yes | Yes |
| Form Validation | No | Yes |
| API Validation | No | Yes |
Each tool solves a different problem.
TypeScript
Zod
Together they provide complete type safety throughout an application.
Many modern React applications use:
React
+
TypeScript
+
Zod
+
React Hook Form
This combination provides:
User Input
│
▼
React Hook Form
│
▼
Zod Validation
│
▼
Valid Data
│
▼
TypeScript Types
│
▼
API Request
Every stage ensures the data remains valid.
Throughout this course, our primary focus will be:
TypeScript
+
Zod
TypeScript ensures code correctness during development.
Zod ensures data correctness while the application is running.
Together they form the modern standard for building reliable React applications.
TypeScript catches many errors before they become bugs and improves the overall development experience.
Instead of repeating object structures, create reusable interfaces.
interface User {
id: number;
name: string;
}
Always validate data coming from:
Never assume external data is correct.
safeParse() for User InputInstead of allowing your application to crash, use:
safeParse()
to safely validate data and display user-friendly error messages.
Instead of creating multiple validation rules for the same data, define one reusable schema.
This keeps validation consistent throughout the application.
| Tool | Purpose |
|---|---|
| TypeScript | Static Type Checking |
| Interface | Define Object Structure |
| Type | Define Data Types |
| Zod | Runtime Validation |
| Schema | Data Validation Rules |
| parse() | Validate Data |
| safeParse() | Validate Without Throwing |
Modern React applications commonly use:
React
│
▼
TypeScript
│
▼
Zod
│
▼
React Hook Form
Each tool has a specific responsibility:
Together they provide:
This combination has become the standard approach for building modern, scalable React applications.