Skip to content

TS2322: Type 'null' is not assignable to type 'string'

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.


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'

const username: string = getStoredValue() ?? "default"; // ✅
const value = getStoredValue();
if (value !== null) {
const username: string = value; // ✅
}
const username: string | null = getStoredValue(); // ✅

const token: string = localStorage.getItem('token');
// ❌ Type 'string | null' is not assignable
// ✅ Fix:
const token: string = localStorage.getItem('token') ?? "";
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");
}

  • null and undefined are different types in TypeScript
  • Use ?? "" for default values
  • Use type guards (!== null) for safety
  • Avoid ! unless absolutely certain