Skip to main content

Conditional Rendering in TypeScript

Level: Beginner to Intermediate

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

Conditional Rendering 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 guards and discriminated unions enable safe conditional rendering with type narrowing.

Prerequisite: Read React JS article 10 first.

The Problem

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

Type Guards (Predicates)

// Basic type guard
function isStudent(data: unknown): data is Student {
return (
typeof data === 'object' &&
data !== null &&
'id' in data &&
'name' in data &&
'className' in data
);
}

function isTeacher(data: unknown): data is Teacher {
return (
typeof data === 'object' &&
data !== null &&
'employeeCode' in data
);
}

function PersonCard({ person }: { person: Student | Teacher | null }) {
if (!person) return <p>No person</p>;

if (isStudent(person)) {
return <p>{person.name} - Class {person.className}</p>;
}

if (isTeacher(person)) {
return <p>{person.name} - Code {person.employeeCode}</p>;
}

return null; // Never reached, but TypeScript knows
}

Discriminated Unions

// Union with discriminating field
type DataState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'error'; error: Error }
| { status: 'success'; data: T };

function StudentDetail() {
const [state, setState] = useState<DataState<Student>>({ status: 'idle' });

// TypeScript narrows type based on status
if (state.status === 'loading') {
return <p>Loading...</p>;
}

if (state.status === 'error') {
return <p>Error: {state.error.message}</p>;
}

if (state.status === 'success') {
return <p>{state.data.name}</p>;
}

return null;
}

Exhaustiveness Checking

type Status = 'pending' | 'approved' | 'rejected';

function StatusBadge({ status }: { status: Status }) {
switch (status) {
case 'pending':
return <span className="badge-yellow">Pending</span>;
case 'approved':
return <span className="badge-green">Approved</span>;
case 'rejected':
return <span className="badge-red">Rejected</span>;
// ❌ Error if you forgot a case
// default: return null;
}
}

Optional Chaining with Types

interface StudentDetail {
id: number;
name: string;
marks?: number;
parent?: {
name: string;
phone?: string;
};
}

function StudentInfo({ student }: { student: StudentDetail }) {
return (
<div>
<h3>{student.name}</h3>
{student.marks && <p>Marks: {student.marks}</p>}
{student.parent?.name && <p>Parent: {student.parent.name}</p>}
{student.parent?.phone && <p>Phone: {student.parent.phone}</p>}
</div>
);
}

As Const for Literal Types

const ROLES = ['admin', 'teacher', 'student'] as const;
type Role = typeof ROLES[number]; // 'admin' | 'teacher' | 'student'

function RoleCard({ role }: { role: Role }) {
const roleInfo: Record<Role, string> = {
admin: 'Administrator',
teacher: 'Teacher',
student: 'Student'
};

return <div>{roleInfo[role]}</div>;
}

Complex Conditional

interface ViewProps {
user: User;
isOwner: boolean;
isAdmin: boolean;
}

function StudentActions({ user, isOwner, isAdmin }: ViewProps) {
return (
<div>
<button>View</button>

{(isOwner || isAdmin) && (
<>
<button>Edit</button>
{isAdmin && <button>Delete</button>}
</>
)}
</div>
);
}

Type-Safe Render Props

interface RenderProps {
status: 'loading' | 'error' | 'success';
data?: Student;
error?: Error;
}

interface StudentDetailProps {
studentId: number;
render: (props: RenderProps) => React.ReactNode;
}

function StudentDetail({ studentId, render }: StudentDetailProps) {
const [state, setState] = useState<DataState<Student>>({ status: 'loading' });

useEffect(() => {
fetch(`/api/students/${studentId}`)
.then(r => r.json())
.then(data => setState({ status: 'success', data }))
.catch(error => setState({ status: 'error', error }));
}, [studentId]);

const props: RenderProps = state.status === 'success'
? { status: 'success', data: state.data }
: state.status === 'error'
? { status: 'error', error: state.error }
: { status: 'loading' };

return <>{render(props)}</>;
}

// Usage
<StudentDetail
studentId={1}
render={({ status, data, error }) => {
if (status === 'loading') return <p>Loading...</p>;
if (status === 'error') return <p>{error?.message}</p>;
return <p>{data?.name}</p>;
}}
/>

Key Takeaways

  • Type guards narrow types safely
  • Discriminated unions enable exhaustiveness
  • Optional chaining prevents null errors
  • Literal types ensure valid values
  • Type narrowing in conditionals
  • Next: Error handling with types
⚠️ Conditional Mistakes
  1. Missing type guard check — data could be any type
  2. Incomplete unions — Not all cases handled
  3. Not narrowing — TypeScript doesn't know type changed
  4. Any in conditionals — Defeats type safety
💡 Never Type

Use never for exhaustiveness:

const impossible: never = state; // Error if state not exhausted
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Type Guards. Try these prompts:

  • "How do type guards enable type narrowing?"
  • "What's a discriminated union?"
  • "Why use as const for literal types?"
  • "Quiz me on conditional 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

  • Conditional Rendering 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 Conditional Rendering 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 Conditional Rendering 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 Conditional Rendering in TypeScript in an interview?

Conditional Rendering 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

Error Handling in TypeScript ->

nexcoding.in