02. TypeScript Essentials for React
Level: Beginner to Intermediate
- Basic TypeScript types (string, number, boolean, any, union)
- Interfaces: defining object shapes
- Generics for reusable typed components
- Type aliases and when to use them
- Common React+TS patterns
- Type SMS Student interface properly
The Problem
React + TypeScript catches errors before runtime. When the backend API changes the Student response shape, TypeScript tells you immediately. When a component expects a string but gets null, TypeScript errors. These errors are cheap to fix during development, expensive to debug in production.
TypeScript is JavaScript with types. Same JavaScript features, now with type safety.
Prerequisite: Read React JS article 02 (JavaScript Essentials) first.
Basic Types
// Primitive types
const name: string = "Ravi Kumar";
const marks: number = 95;
const isActive: boolean = true;
const age: number | undefined = undefined;
// Arrays
const students: string[] = ["Ravi", "Priya"];
const studentMarks: Array<number> = [95, 88, 92];
// Tuples (fixed length, specific types)
const studentInfo: [string, number, boolean] = ["Ravi", 95, true];
// Any (avoid, defeats TypeScript)
const anything: any = "can be anything";
// Unknown (safer than any)
const value: unknown = "some value";
if (typeof value === 'string') {
console.log(value.toUpperCase()); // Safe
}
Functions with Types
// Parameters and return type
function addMarks(exam1: number, exam2: number): number {
return exam1 + exam2;
}
// Optional parameter
function greetStudent(name: string, className?: string): string {
return `${name} - ${className || 'Unknown'}`;
}
// Default parameter
function getStudentList(limit: number = 10): string[] {
return [];
}
// Arrow function with types
const calculateAverage = (marks: number[]): number => {
return marks.reduce((sum, m) => sum + m, 0) / marks.length;
};
Interfaces — Describing Objects
interface Student {
id: number;
name: string;
className: string;
marks: number;
isActive?: boolean; // Optional
}
const student: Student = {
id: 1,
name: "Ravi Kumar",
className: "10",
marks: 95
};
// Function parameter with interface
function displayStudent(student: Student): void {
console.log(`${student.name} - Class ${student.className}`);
}
Types vs Interfaces
Both describe object shapes. Use interface for React components:
// Interface (preferred for components)
interface StudentCardProps {
student: Student;
onDelete?: (id: number) => void;
}
// Type (for unions, primitives)
type StudentStatus = "Active" | "Inactive" | "Graduated";
type Marks = number | string; // Union type
Extending Interfaces
interface Person {
name: string;
email: string;
}
interface Student extends Person {
rollNumber: string;
className: string;
}
const student: Student = {
name: "Ravi",
email: "ravi@school.com",
rollNumber: "NCA-001",
className: "10"
};
Enums — Named Constants
enum StudentStatus {
Active = "Active",
Inactive = "Inactive",
Graduated = "Graduated",
Transferred = "Transferred"
}
enum UserRole {
SuperAdmin = 1,
Admin = 2,
Principal = 3,
Teacher = 4,
Student = 5
}
const status: StudentStatus = StudentStatus.Active;
const role: UserRole = UserRole.Teacher;
Generics — Reusable Types
// Generic function
function getItem<T>(items: T[], index: number): T {
return items[index];
}
const studentName = getItem<string>(["Ravi", "Priya"], 0); // "Ravi"
const mark = getItem<number>([95, 88], 1); // 88
// Generic interface
interface ApiResponse<T> {
success: boolean;
data: T;
message?: string;
}
interface StudentData {
id: number;
name: string;
}
const response: ApiResponse<StudentData> = {
success: true,
data: { id: 1, name: "Ravi" }
};
// Generic with constraints
interface HasId {
id: number;
}
function printId<T extends HasId>(item: T): void {
console.log(item.id);
}
printId({ id: 1, name: "Ravi" }); // OK
// printId({ name: "Ravi" }); // Error: missing id
Union Types
type StudentStatus = "Active" | "Inactive" | "Graduated";
type IdType = number | string;
const status: StudentStatus = "Active";
const studentId: IdType = "NCA-001";
// Function with union
function processId(id: number | string): string {
if (typeof id === 'number') {
return `ID: ${id}`;
}
return `Code: ${id}`;
}
Intersection Types
interface Name {
firstName: string;
lastName: string;
}
interface Age {
age: number;
}
type Person = Name & Age;
const person: Person = {
firstName: "Ravi",
lastName: "Kumar",
age: 35
};
Utility Types
Partial — Make all optional
interface Student {
id: number;
name: string;
className: string;
}
type PartialStudent = Partial<Student>;
const update: PartialStudent = {
name: "Ravi Updated"
}; // OK, no need for all fields
Required — Make all required
type RequiredStudent = Required<PartialStudent>;
// Now all fields are required
Record — Map keys to values
type StudentStatus = "Active" | "Inactive" | "Graduated";
const studentCount: Record<StudentStatus, number> = {
Active: 150,
Inactive: 10,
Graduated: 200
};
Pick — Select specific fields
type StudentPreview = Pick<Student, 'name' | 'className'>;
const preview: StudentPreview = {
name: "Ravi",
className: "10"
};
Omit — Exclude specific fields
type StudentWithoutId = Omit<Student, 'id'>;
const student: StudentWithoutId = {
name: "Ravi",
className: "10",
marks: 95
};
Array Methods with Types
interface Student {
id: number;
name: string;
marks: number;
}
const students: Student[] = [
{ id: 1, name: "Ravi", marks: 95 },
{ id: 2, name: "Priya", marks: 88 }
];
// map with types
const names: string[] = students.map(s => s.name);
// filter with types
const topStudents: Student[] = students.filter(s => s.marks >= 90);
// find with types
const ravi: Student | undefined = students.find(s => s.name === "Ravi");
Type Assertions (Use Carefully)
// Cast to specific type
const value: any = "hello";
const length = (value as string).length;
// or
const length2 = (<string>value).length; // Older syntax
Key Takeaways
- Types prevent runtime errors
- Interfaces describe object shapes
- Generics make reusable types
- Utility types speed up development
- Same JavaScript, now with types
- Next: JSX with TypeScript
- Using
any— Defeats TypeScript purpose - Over-typing — Not everything needs a type
- Type assertions — Don't use when you're unsure
- Ignoring errors — Fix them, don't suppress
TypeScript concepts are familiar from C#:
interface→ same as C#string | number→ like C# nullablestring?<T>generics → same syntax- Enums → same as C# enums
Use ChatGPT, Claude, or Copilot to go deeper on TypeScript Fundamentals. Try these prompts:
"What's the difference between interface and type?""When would you use generics?""What utility types make TypeScript easier?""Quiz me on TypeScript essentials"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.
Quick Definitions
- TypeScript Essentials for React - The main React + TypeScript concept explained in this lesson.
- Type/interface - A contract that describes the shape of data.
- Typed props/state - React data with clear compile-time expectations.
- API DTO - The request or response shape shared with ASP.NET Core Web API.
Common Mistakes
- Using
anytoo quickly instead of defining a useful type - Typing props loosely and losing the benefit of TypeScript
- Forgetting that API data can still be missing or invalid at runtime
- Making types too complex before the component is stable
- Not sharing clear DTO shapes between frontend and backend teams
Practice Task
Create a small React TypeScript example using TypeScript Essentials for React. Keep it connected to a School Management System scenario.
Suggested practice:
- Define a clear
Student,Teacher, orAttendancetype. - Build a small typed component or hook.
- Add one valid example and one intentionally wrong example to see TypeScript errors.
- Explain the type contract in your own words.
- Rebuild the same example once without looking at the article.
Quick Revision
| Question | Answer |
|---|---|
| What is the main idea? | Use TypeScript to make TypeScript Essentials for React safer in React. |
| Where is it used? | Props, state, forms, API responses, context, hooks, and routes. |
| What should beginners avoid? | Overusing any and ignoring runtime API validation. |
| What is the best debugging habit? | Read the TypeScript error, check the data shape, and fix the type contract. |
TypeScript Essentials for React is a React + TypeScript concept that improves safety and maintainability. I would explain which values need types, how TypeScript catches mistakes early, and how it helps when consuming ASP.NET Core Web API responses.
It is used in typed props, API response models, form state, route parameters, context values, custom hooks, and reusable UI components.