Skip to main content

Routing in TypeScript

Level: Beginner to Intermediate

ℹ️ What You'll Learn
  • What Routing in TypeScript means in React + TypeScript
  • How type safety improves React components
  • How to model School Management System data with interfaces and types
  • Common TypeScript mistakes to avoid
  • How to explain this topic in interviews

Why This Matters

Routing in TypeScript helps you build React screens with fewer runtime bugs. In real .NET Web API projects, TypeScript makes API DTOs, component props, form state, and shared data contracts easier to understand and safer to change.

Type-safe routing prevents invalid navigation and ensures params are handled correctly.

Prerequisite: Read React JS article 13 first.

The Problem

React JavaScript can fail at runtime when props, API responses, or form values have the wrong shape. This lesson shows how Routing in TypeScript uses TypeScript to catch many of those mistakes while you write code, before the student dashboard reaches users.

Typed Route Parameters

interface StudentDetailParams {
id: string;
}

function StudentDetail() {
const { id } = useParams<StudentDetailParams>();
const studentId = id ? parseInt(id, 10) : 0;

if (!studentId) return <p>Invalid student ID</p>;

return <div>Student {studentId}</div>;
}

Typed Navigation

function StudentCard({ student }: { student: Student }) {
const navigate = useNavigate();

const handleView = (): void => {
navigate(`/students/${student.id}`);
};

const handleEdit = (): void => {
navigate(`/students/${student.id}/edit`);
};

return (
<div>
<button onClick={handleView}>View</button>
<button onClick={handleEdit}>Edit</button>
</div>
);
}

Typed Routes Setup

interface AppRoutes {
home: '/';
students: '/students';
studentDetail: `/students/:id`;
studentEdit: `/students/:id/edit`;
teachers: '/teachers';
teacherDetail: `/teachers/:id`;
}

// Type-safe route builder
const routes: Record<keyof AppRoutes, string> = {
home: '/',
students: '/students',
studentDetail: '/students/:id',
studentEdit: '/students/:id/edit',
teachers: '/teachers',
teacherDetail: '/teachers/:id'
};

function App() {
return (
<BrowserRouter>
<Routes>
<Route path={routes.home} element={<Home />} />
<Route path={routes.students} element={<StudentList />} />
<Route path={routes.studentDetail} element={<StudentDetail />} />
<Route path={routes.studentEdit} element={<StudentEdit />} />
<Route path={routes.teachers} element={<TeacherList />} />
</Routes>
</BrowserRouter>
);
}
function buildStudentUrl(id: number): string {
return `/students/${id}`;
}

function buildStudentEditUrl(id: number): string {
return `/students/${id}/edit`;
}

function StudentCard({ student }: { student: Student }) {
return (
<>
<Link to={buildStudentUrl(student.id)}>View</Link>
<Link to={buildStudentEditUrl(student.id)}>Edit</Link>
</>
);
}

Complex Route Params

interface SearchParams {
class: string;
status: string;
sort: 'name' | 'marks';
}

function StudentList() {
const [searchParams, setSearchParams] = useSearchParams();

const className = searchParams.get('class') || '';
const status = searchParams.get('status') || '';
const sort = (searchParams.get('sort') || 'name') as 'name' | 'marks';

const handleFilterChange = (newClass: string): void => {
setSearchParams({ class: newClass, status, sort });
};

return (
<div>
<select value={className} onChange={e => handleFilterChange(e.target.value)}>
<option value="">All</option>
<option value="10">Class 10</option>
<option value="11">Class 11</option>
</select>
</div>
);
}

Protected Routes with Types

interface ProtectedRouteProps {
element: React.ReactElement;
isAuthenticated: boolean;
userRole?: 'admin' | 'teacher' | 'student';
requiredRole?: 'admin' | 'teacher';
}

function ProtectedRoute({
element,
isAuthenticated,
userRole,
requiredRole
}: ProtectedRouteProps) {
if (!isAuthenticated) {
return <Navigate to="/" replace />;
}

if (requiredRole && (!userRole || userRole !== requiredRole)) {
return <Navigate to="/unauthorized" replace />;
}

return element;
}

// Usage
<Routes>
<Route path="/admin" element={
<ProtectedRoute
element={<AdminPanel />}
isAuthenticated={isAuth}
userRole={role}
requiredRole="admin"
/>
} />
</Routes>

Key Takeaways

  • Type route params with interfaces
  • Create route constant records
  • Type navigate callbacks
  • Type search params
  • Protect routes safely
  • Next: Context with types
⚠️ Routing Mistakes
  1. Wrong param type — id is string, not number
  2. Forgetting to parseparseInt(id) before using
  3. Invalid routes — No type checking on paths
  4. No protected routes — Anyone can access
💡 Route Constants

Define routes once, use everywhere:

const ROUTES = {
students: '/students',
studentDetail: (id: number) => `/students/${id}`
};

<Link to={ROUTES.studentDetail(1)} />
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Typed Routing. Try these prompts:

  • "Why type route params?"
  • "How do you protect routes?"
  • "When use route constants?"
  • "Quiz me on routing types"

💡 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

  • Routing in TypeScript - 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 any too 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 Routing in TypeScript. Keep it connected to a School Management System scenario.

Suggested practice:

  1. Define a clear Student, Teacher, or Attendance type.
  2. Build a small typed component or hook.
  3. Add one valid example and one intentionally wrong example to see TypeScript errors.
  4. Explain the type contract in your own words.
  5. Rebuild the same example once without looking at the article.

Quick Revision

QuestionAnswer
What is the main idea?Use TypeScript to make Routing in TypeScript 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.
🎯 How would you explain Routing in TypeScript in an interview?

Routing in TypeScript 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.

🎯 Where is this used in a real React TypeScript project?

It is used in typed props, API response models, form state, route parameters, context values, custom hooks, and reusable UI components.

Next Article

Context API in TypeScript ->

nexcoding.in