Course contentsShow
← React
Lesson 2381 of 2,39651. TypeScript with React BasicsFree lesson

Typing useState: Explicit Type Arguments

Learn when and how to provide type arguments to useState for non-primitive or union types.

Typing useState: Explicit Type Arguments

What you'll learn: When useState needs explicit type arguments and how to provide them for complex or union types.

The Type Inference Limitation

TypeScript usually infers useState types from the initial value—if you write useState(0), TypeScript knows it's number. But when your state can hold multiple types or starts as null/undefined, inference fails. You'll end up with types that are too narrow or awkward to work with.

When You Need Explicit Types

Provide type arguments to useState when:

  • Initial value is null or undefined: useState(null) infers null forever
  • Union types: State can be multiple different types
  • Complex object shapes: You want to enforce a specific structure
  • Arrays of specific types: Beyond simple primitives

The Syntax

// Without explicit type: stuck as null
const [user, setUser] = useState(null); // Type: null

// With explicit type: can be User or null
const [user, setUser] = useState<User | null>(null); // Type: User | null

Common Patterns

// Union of string literals
const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');

// Array of specific type
const [items, setItems] = useState<Product[]>([]);

// Complex object with optional properties
interface FormState {
  name: string;
  email?: string;
}
const [form, setForm] = useState<FormState>({ name: '' });

Think of explicit type arguments as telling TypeScript: "I know this starts simple, but it's actually going to hold something bigger." Without them, TypeScript assumes the initial value defines the entire possible range.

Key Takeaway: Use useState<Type>(initialValue) when TypeScript can't infer the full range of possible values from the initial state, especially with unions, nullable types, or complex structures.