Curriculum
Course: TypeScript
Login
Text lesson

TS Null

TypeScript has a robust system for handling null or undefined values.

By default, handling of null and undefined is disabled, and can be enabled by setting strictNullChecks to true.

 

The rest of this page pertains to scenarios where strictNullChecks is enabled.

Types

null and undefined are primitive types and can be used similarly to other types, such as string.

Example

let value: string | undefined | null = null;
value = ‘hello’;
value = undefined;

When strictNullChecks is enabled, TypeScript requires values to be set unless undefined is explicitly included in the type.

Optional Chaining

Optional Chaining integrates seamlessly with TypeScript’s null handling, enabling concise property access on objects that might not exist. Using the ?. operator, it streamlines conditional property access, enhancing both readability and safety when dealing with nullable types.

Example

interface House {
  sqft: number;
  yard?: {
    sqft: number;
  };
}
function printYardSize(house: House) {
  const yardSize = house.yard?.sqft;
  if (yardSize === undefined) {
    console.log(‘No yard’);
  } else {
    console.log(`Yard is ${yardSize} sqft`);
  }
}

let home: House = {
  sqft: 500
};

printYardSize(home); // Prints ‘No yard’

Nullish Coalescence

Nullish Coalescence is another JavaScript feature that works well with TypeScript’s null handling. It provides a way to specify fallback values specifically for null or undefined. This is useful when other falsy values might occur in the expression but are still valid. It uses the ?? operator in an expression, similar to how the && operator is used.

Example

function printMileage(mileage: number | null | undefined) {
  console.log(`Mileage: ${mileage ?? ‘Not Available’}`);
}

printMileage(null); // Prints ‘Mileage: Not Available’
printMileage(0); // Prints ‘Mileage: 0’

Null Assertion

TypeScript’s inference system isn’t infallible, and sometimes it’s necessary to disregard a value’s potential to be null or undefined. While casting can achieve this, TypeScript also offers the ! operator as a convenient shortcut for such cases.

Example

function getValue(): string | undefined {
  return ‘hello’;
}
let value = getValue();
console.log(‘value length: ‘ + value!.length);

Similar to casting, using the ! operator can be unsafe and should be done with caution.

Array bounds handling

Even with strictNullChecks enabled, TypeScript assumes that array access will not return undefined by default (unless undefined is part of the array type). To change this behavior, use the noUncheckedIndexedAccess configuration.

Example

let array: number[] = [123];
let value = array[0]; // with `noUncheckedIndexedAccess` this has the type `number | undefined`