Course contentsShow
← TypeScript
Lesson 100 of 1,7963. Basic TypesFree lesson

strictNullChecks and Primitive Assignability

Learn how this flag affects whether null and undefined are valid for other types.

strictNullChecks and Primitive Assignability

You'll learn how the strictNullChecks flag changes whether null and undefined can be assigned to other primitive types.

The Core Idea

By default, TypeScript treats null and undefined as valid values for any type. You can assign them to string, number, boolean, or any other type without error. This matches JavaScript's behavior but creates opportunities for runtime errors.

When you enable strictNullChecks (which is included in strict: true), TypeScript suddenly treats null and undefined as their own distinct types. Now you can only assign them to variables explicitly typed to accept them.

Without strictNullChecks

let name: string = "Alice";
name = null; // Allowed — no error
name = undefined; // Also allowed

let count: number = 42;
count = null; // Allowed

Everything compiles, but your code might crash at runtime when you try to use these values.

With strictNullChecks

let name: string = "Alice";
name = null; // Error: Type 'null' is not assignable to type 'string'
name = undefined; // Error: Type 'undefined' is not assignable to type 'string'

let count: number = 42;
count = null; // Error: Type 'null' is not assignable to type 'number'

Now TypeScript catches these potential issues at compile time. If you want to allow null or undefined, you must say so explicitly using the type annotation syntax you've learned.

Why This Matters

Think of strictNullChecks as a safety net. Without it, TypeScript lets "nothing" masquerade as "something." With it enabled, you're forced to acknowledge when absence is possible, making your code much safer.

Key Takeaway: strictNullChecks prevents null and undefined from being silently assigned to other primitive types, catching potential runtime errors at compile time.