null and undefined

Two Kinds of Nothing

  • undefined: a value was never set (missing property, missing argument, uninitialised variable).
  • null: a value was set to "nothing" on purpose.
  • With strict mode (strictNullChecks), null and undefined are NOT allowed in a string or number variable. You must say so with a union like string | null.

Example

Example

The middle name may be missing, so its type is string | null. TypeScript makes you check it before use.

let middleName: string | null = null;
let nickname: string | undefined;

function fullName(first: string, middle: string | null, last: string): string {
  return middle === null ? `${first} ${last}` : `${first} ${middle} ${last}`;
}

console.log(fullName("Rahul", middleName, "Sharma"));
middleName = "Kumar";
console.log(fullName("Rahul", middleName, "Sharma"));
console.log(nickname);

Output

Rahul Sharma
Rahul Kumar Sharma
undefined

strictNullChecks in Action

Example

Assigning null to a plain string is an error (TS2322). This one rule prevents the famous "Cannot read properties of null" crash.

let city: string = "Chennai";
city = null;

Compiler output (tsc)

Line 2: error TS2322: Type 'null' is not assignable to type 'string'.

Tip: Always keep "strict": true in tsconfig.json. Without it, TypeScript lets null go anywhere and you lose most of the safety.