Skip to main content

Error Handling in TypeScript

Level: Beginner to Intermediate

ℹ️ What You'll Learn
  • What Error Handling 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

Error Handling 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 error handling prevents runtime surprises.

Prerequisite: Read React JS article 11 first.

The Problem

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

Typed Error Catching

try {
const response = await fetch('/api/students');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data: Student[] = await response.json();
} catch (err: unknown) {
if (err instanceof Error) {
console.error('Error:', err.message);
} else {
console.error('Unknown error:', err);
}
}

Custom Error Types

interface ApiError {
status: number;
message: string;
code: string;
}

async function fetchStudent(id: number): Promise<Student> {
const response = await fetch(`/api/students/${id}`);

if (!response.ok) {
const error: ApiError = await response.json();
throw new Error(`[${error.code}] ${error.message}`);
}

return response.json();
}

Error Boundary with Types

interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
}

class ErrorBoundary extends React.Component<
{ children: React.ReactNode },
ErrorBoundaryState
> {
constructor(props: { children: React.ReactNode }) {
super(props);
this.state = { hasError: false, error: null };
}

static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}

render() {
if (this.state.hasError) {
return <p>Error: {this.state.error?.message}</p>;
}
return this.props.children;
}
}

Async Error State

interface ErrorState {
data: Student | null;
loading: boolean;
error: Error | null;
}

function StudentDetail({ studentId }: { studentId: number }) {
const [state, setState] = useState<ErrorState>({
data: null,
loading: true,
error: null
});

useEffect(() => {
fetch(`/api/students/${studentId}`)
.then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
})
.then((data: Student) => setState({ data, loading: false, error: null }))
.catch((error: unknown) => {
const err = error instanceof Error ? error : new Error('Unknown');
setState({ data: null, loading: false, error: err });
});
}, [studentId]);

if (state.loading) return <p>Loading...</p>;
if (state.error) return <p>Error: {state.error.message}</p>;
return <div>{state.data?.name}</div>;
}

Error Mapping

const getErrorMessage = (status: number): string => {
const messages: Record<number, string> = {
400: 'Invalid request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not found',
500: 'Server error'
};

return messages[status] || 'Unknown error';
};

// Usage
try {
const response = await fetch('/api/students');
if (!response.ok) {
const message = getErrorMessage(response.status);
throw new Error(message);
}
} catch (err) {
// Type narrowed
}

Key Takeaways

  • Type caught errors as unknown
  • Create custom error interfaces
  • Error state in useState
  • Map HTTP codes to messages
  • Error boundaries for crashes
  • Next: API integration with types
⚠️ Error Handling Mistakes
  1. Catching any — Loses type safety
  2. Not checking err type — Could crash on non-Error
  3. Ignoring errors — Users confused
  4. Not mapping codes — Generic messages unhelpful
💡 Safe Error Check
if (err instanceof Error) {
// Now you know it's an Error
console.error(err.message);
}
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Error Types. Try these prompts:

  • "Why catch as unknown?"
  • "How do you type custom errors?"
  • "When use error boundaries?"
  • "Quiz me on error 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

  • Error Handling 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 Error Handling 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 Error Handling 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 Error Handling in TypeScript in an interview?

Error Handling 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

API Integration in TypeScript ->

nexcoding.in