Optional vs Required: The Username Example
What you'll learn: How making username optional when logged out and required when logged in prevents your type system from allowing impossible states.
The Problem with Always-Optional Properties
Imagine modeling a user object where username is always optional:
interface User {
id: string;
username?: string;
email: string;
}
This seems reasonable—guests don't have usernames—but it creates a dangerous gap: your logged-in users might accidentally have no username, and TypeScript won't stop you from treating logged-out users as if they do.
Every time you access user.username, you must check for undefined, even when you know the user is authenticated. This is the impossible state problem: the type allows combinations that shouldn't exist in your domain.
The Solution: Separate States with Discriminated Unions
Instead of one flexible type, create two distinct states:
type User =
| { status: 'guest'; id: string; email: string }
| { status: 'authenticated'; id: string; username: string; email: string };
Now username is required when authenticated and absent when guest. You cannot construct a logged-in user without a username, and you cannot mistakenly access a username that doesn't exist without TypeScript catching it.
When switching on status, TypeScript knows exactly which properties are available—no defensive ?. checks needed where they don't belong.
Key Takeaway: Making properties optional when they should only exist in certain states creates impossible states. Use discriminated unions to make username required exactly when it should exist, and TypeScript will prevent every impossible combination.