Course contentsShow
← TypeScript
Lesson 1520 of 1,79635. TypeScript with Framework Cross-ReferencesFree lesson

Typing useState with Generic Type Arguments

Explicitly type state when TypeScript cannot infer the correct type from initial values.

Typing useState with Generic Type Arguments

What you'll learn: How to explicitly tell TypeScript the type of state when it can't figure it out from the initial value alone.


Why This Matters

You've already seen that TypeScript infers types automatically — when you write useState(0), TypeScript knows your state is a number. But sometimes the initial value doesn't tell the whole story. What if you start with null but later want to store a User object? Without help, TypeScript will think your state is only null forever.

The Generic Type Argument Solution

useState is a generic function — it accepts a type parameter that tells it what type of values the state will hold. When inference isn't enough, you provide this type explicitly:

const [user, setUser] = useState<User | null>(null);

Now TypeScript knows the state can be either a User object or null, even though you initialized it with just null.

When You Need This

Scenario 1: Starting with null or undefined

// ❌ TypeScript infers: null (forever)
const [data, setData] = useState(null);

// ✅ Explicit type: User | null
const [data, setData] = useState<User | null>(null);

Scenario 2: Empty arrays

// ❌ Inferred as: never[]
const [items, setItems] = useState([]);

// ✅ Explicit type: string[]
const [items, setItems] = useState<string[]>([]);

Scenario 3: Complex union types

// ✅ State can be one of three values
const [status, setStatus] = useState<'idle' | 'loading' | 'success'>('idle');

The Type Flows Through

Once you've set the generic type argument, TypeScript enforces it everywhere:

const [count, setCount] = useState<number | null>(null);

setCount(42);      // ✅ Valid
setCount(null);    // ✅ Valid
setCount("hello"); // ❌ Error: string not assignable

Key Takeaway: Use generic type arguments with useState<T>() when the initial value doesn't fully represent all possible state values, especially with null, undefined, empty arrays, or union types.