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

null and undefined as Types

Understand how null and undefined are both values and their own distinct types.

null and undefined as Types

What you'll learn: How null and undefined are both runtime values and their own distinct types in TypeScript.

The Dual Nature of null and undefined

In JavaScript, null and undefined are special values that represent "nothingness" or "absence of value." TypeScript treats them uniquely: they're not just values you can assign—they're also types themselves.

When you write null as a type annotation, you're creating a type that can only hold the value null. The same goes for undefined—it's both the value and the only member of its own type.

let explicitNull: null = null;
let explicitUndefined: undefined = undefined;

// These are the ONLY values each type can hold
explicitNull = undefined;  // Error!
explicitUndefined = null;  // Error!

Why This Matters

This design allows TypeScript to track exactly which values might be absent. When you declare a variable as string, by default (in strict mode), it cannot be null or undefined—those are separate, incompatible types.

let name: string = "Alice";
name = null;       // Error in strict mode!
name = undefined;  // Error in strict mode!

If you want to allow null or undefined, you must explicitly say so (we'll learn how later).

Think of It Like This

Imagine null and undefined as exclusive clubs. The null club has exactly one member (the value null), and the undefined club has exactly one member (the value undefined). These clubs don't overlap with the string, number, or boolean clubs—they're completely separate.

Key Takeaway: In TypeScript, null and undefined are both values you can use and distinct types that only accept their own single value, keeping them separate from other types like string or number.