Quick Answer

TypeScript strict null checking

Understanding the Issue

With strictNullChecks enabled, TypeScript requires explicit handling of possibly null/undefined values before they can be used.

The Problem

This code demonstrates the issue:

Typescript Error
// Problem: Unsafe access
function getLength(s: string | null) {
    return s.length; // Error
}

The Solution

Here's the corrected code:

Typescript Fixed
// Solution 1: Null check
function getLength(s: string | null) {
    return s ? s.length : 0;
}

// Solution 2: Type assertion
function getLength(s: string | null) {
    return s!.length; // Unsafe if null

// Solution 3: Optional chaining
const len = obj?.prop?.length; // Returns undefined if any access fails

Key Takeaways

Always handle possible null/undefined values explicitly.