TS2322: Type 'null' is not assignable to type 'string'
What’s happening?
Section titled “What’s happening?”This error occurs when a value that may be null is assigned to a variable that expects a strict type (like string).
With strictNullChecks enabled, TypeScript treats null as a distinct type.
Reproduction
Section titled “Reproduction”function getStoredValue(): string | null { const stored = localStorage.getItem('username'); return stored; // Can be null}
const username: string = getStoredValue();// ❌ Type 'null' is not assignable to type 'string'Solutions
Section titled “Solutions”Option 1: Nullish coalescing operator
Section titled “Option 1: Nullish coalescing operator”const username: string = getStoredValue() ?? "default"; // ✅Option 2: Type narrowing
Section titled “Option 2: Type narrowing”const value = getStoredValue();if (value !== null) { const username: string = value; // ✅}Option 3: Update the type
Section titled “Option 3: Update the type”const username: string | null = getStoredValue(); // ✅Common scenarios
Section titled “Common scenarios”localStorage
Section titled “localStorage”const token: string = localStorage.getItem('token');// ❌ Type 'string | null' is not assignable
// ✅ Fix:const token: string = localStorage.getItem('token') ?? "";Database queries
Section titled “Database queries”const user: User = await db.findOne({ id: 1 });// ❌ Type 'User | null' is not assignable
// ✅ Fix:const user = await db.findOne({ id: 1 });if (user === null) { throw new Error("User not found");}Key takeaways
Section titled “Key takeaways”nullandundefinedare different types in TypeScript- Use
?? ""for default values - Use type guards (
!== null) for safety - Avoid
!unless absolutely certain