Course contentsShow
← TypeScript
Lesson 1339 of 1,79631. Type-Driven DesignFree lesson

Splitting Types by Context

Creating separate LoggedInUser and AnonymousUser types instead of one User with optional fields.

Splitting Types by Context

You'll learn: How to replace one bloated type with multiple context-specific types to eliminate impossible states and clarify intent.


The Problem with One-Size-Fits-All Types

Imagine a single User type with fields like username?, sessionToken?, and preferences?—all optional because different parts of your app need different subsets. This creates a minefield: you can't tell from the type alone which fields are actually present in each situation.

type User = {
  id: string;
  username?: string;
  sessionToken?: string;
  lastLogin?: Date;
  isGuest?: boolean;
};

In your dashboard component, you know the user is logged in, so username and sessionToken should be guaranteed. But the type says they're optional. You end up writing defensive checks everywhere, or worse—assuming they exist and facing runtime errors.


Split by Context

The solution: create separate types for each context where the requirements differ.

type LoggedInUser = {
  id: string;
  username: string;
  sessionToken: string;
  lastLogin: Date;
};

type AnonymousUser = {
  id: string;
  isGuest: true;
};

Now your dashboard can accept LoggedInUser, making username and sessionToken required. Your homepage can accept AnonymousUser, which has no session data at all. No optional fields, no guessing, no impossible states.


Why This Works

By splitting types, you:

  • Eliminate optional properties where they don't belong
  • Make function signatures honest about what they need
  • Catch mistakes at compile time when the wrong user type is passed
  • Communicate intent clearly to other developers (and your future self)

If a function accepts LoggedInUser, you know exactly what's guaranteed. The type becomes documentation and enforcement in one.


Key Takeaway: Instead of one type with many optional fields, create separate types for each usage context—making the required properties explicit and impossible states impossible.