How to fix Type 'null' is not assignable to type 'string' in TypeScript

TypeScriptINTERMEDIATEMEDIUMUpdated Dec 11, 2025ยท 124 views

This TypeScript error occurs when strictNullChecks is enabled and you try to assign a null value to a variable or parameter typed as string. The fix involves using union types, type guards, or the non-null assertion operator.

Quick fix

Fixes Type 'null' is not assignable to type 'string'

// Before - causes error
let username: string = null; // Error!

// After - explicitly allow null
let username: string | null = null; // OK
  1. Use union types to explicitly allow null
  2. Add null checks with type guards
  3. Use the nullish coalescing operator (??)
  4. Apply the non-null assertion operator (!) when certain
typescript โ€” error
// Before - causes error
let username: string = null; // Error!
// After - explicitly allow null
let username: string | null = null; // OK
Type 'null' is not assignable to type 'string'

What this error means

This error appears when TypeScript's strict null checking mode is enabled (via the `strictNullChecks` compiler option or the broader `strict` flag). In this mode, `null` and `undefined` are treated as distinct types rather than being automatically assignable to every type. When you attempt to assign a `null` value to a variable, parameter, or property that's explicitly typed as `string`, TypeScript's type checker prevents the assignment because `null` is not a valid `string` value. This is a safety feature introduced in TypeScript 2.0 to catch potential runtime null reference errors at compile time. The error is particularly common when working with DOM APIs (which often return `null`), optional properties, function parameters with default values, or data from external sources where null values are possible. Understanding this error is essential for writing type-safe TypeScript code that prevents null pointer exceptions.

Typical symptoms

  • Compiler error "Type 'null' is not assignable to type 'string'" during build
  • TypeScript error TS2322 in your IDE with red squiggly lines
  • Build fails when trying to assign null to string variables
  • Error when passing possibly-null values to functions expecting strings
  • Issues with DOM element queries that may return null
  • Type errors in Angular FormControl or React state with strict mode enabled

Common causes

  1. strictNullChecks or strict mode is enabled in tsconfig.json
  2. Assigning a literal null value to a string-typed variable
  3. Passing a value typed as string | null to a parameter that only accepts string
  4. DOM API methods like getElementById or querySelector returning Element | null
  5. Optional object properties that could be null being assigned to non-nullable types
  6. Function return types that include null being used where only string is expected
  7. Third-party library types that include null in their type definitions

How to fix "Type 'null' is not assignable to type 'string'"

1Use union types to explicitly allow null

If your value can legitimately be null, update the type to include it:

typescript
// Before - causes error
let username: string = null; // Error!

// After - explicitly allow null
let username: string | null = null; // OK

This is the most type-safe approach when null is a valid value in your application logic.

2Add null checks with type guards

Use conditional statements to narrow the type before assignment:

typescript
function getUserName(user: { name: string | null }): string {
  // Type guard narrows the type
  if (user.name !== null) {
    return user.name; // TypeScript knows it's string here
  }
  return 'Guest'; // Fallback for null case
}

// Or with ternary operator
const displayName = user.name !== null ? user.name : 'Anonymous';

This approach ensures runtime safety and makes your null-handling logic explicit.

3Use the nullish coalescing operator (??)

Provide a default value when the original value is null or undefined:

typescript
// Nullish coalescing provides default value
const username: string = userInput ?? 'DefaultUser';

// Also works with optional chaining
const email: string = user?.email ?? 'no-email@example.com';

// Compared to logical OR, ?? only checks for null/undefined
const count: string = userCount ?? '0'; // Won't trigger for 0 or ''

The ?? operator is cleaner than ternary for simple default value scenarios.

4Apply the non-null assertion operator (!) when certain

If you're absolutely sure a value won't be null at runtime, use the ! operator:

typescript
// When you know the element exists
const button = document.getElementById('submit-btn')!;
button.textContent = 'Click me'; // No error

// With function parameters
function processName(name: string | null) {
  const safeName: string = name!; // Asserts it's not null
  return safeName.toUpperCase();
}

Warning: This bypasses TypeScript's safety checks. Only use when you can guarantee the value is not null, or you'll risk runtime errors.

5Handle DOM APIs with proper null checking

DOM methods often return nullable types. Always check before using:

typescript
// Bad - assumes element exists
const element: HTMLElement = document.getElementById('app'); // Error!

// Good - check for null
const element = document.getElementById('app');
if (element) {
  element.style.color = 'red'; // Safe - TypeScript knows it's not null
}

// Or with type assertion after checking
const element = document.getElementById('app') as HTMLElement;
if (element !== null) {
  element.classList.add('active');
}

This pattern prevents "Cannot read property of null" runtime errors.

6Adjust tsconfig.json if appropriate

If strict null checking isn't needed for your project, you can disable it:

json
{
  "compilerOptions": {
    "strictNullChecks": false,
    // Or disable all strict checks
    "strict": false
  }
}

Note: Disabling strictNullChecks removes important type safety. It's better to fix the root cause than disable the check, but this can be useful during gradual TypeScript migration.

Advanced notes

Strict null checks and type narrowing: TypeScript's control flow analysis automatically narrows types within conditional blocks. After checking if (value !== null), TypeScript knows the value can't be null in that branch. This works with typeof, instanceof, and custom type guard functions.

Union type distribution: When you have a union type like string | null, TypeScript requires you to handle both cases before assigning to a non-nullable type. The type system ensures exhaustive handling through discriminated unions and type guards.

Third-party library types: When using libraries with @types packages, you may encounter this error if the library's type definitions include null in their return types. Use type guards or non-null assertions based on the library's documentation guarantees.

Migration strategies: For large codebases migrating to strict mode, enable strictNullChecks incrementally using TypeScript's skipLibCheck option, then gradually fix files. Tools like ts-migrate can help automate adding necessary null checks.

Performance considerations: Type guards and null checks are compile-time only - they're erased in the JavaScript output and add no runtime overhead. The safety comes from catching errors during development rather than production.

Frequently asked questions

What does "Type 'null' is not assignable to type 'string'" mean?
This error appears when TypeScript's strict null checking mode is enabled (via the strictNullChecks compiler option or the broader strict flag). In this mode, null and undefined are treated as distinct types rather than being automatically assignable to every type. When you attempt to assign a null value to a variable, parameter, or property that's explicitly typed as string, TypeScript's type checker prevents the assignment because null is not a valid string value.
How do I fix "Type 'null' is not assignable to type 'string'"?
This TypeScript error occurs when strictNullChecks is enabled and you try to assign a null value to a variable or parameter typed as string. The fix involves using union types, type guards, or the non-null assertion operator.
What causes "Type 'null' is not assignable to type 'string'"?
strictNullChecks or strict mode is enabled in tsconfig.json Assigning a literal null value to a string-typed variable Passing a value typed as string | null to a parameter that only accepts string
Is the "Type 'null' is not assignable to type 'string'" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading