CodeBlanks Logo Icon CodeBlanks

strictNullChecks deep

Learn the deep behavior of strictNullChecks.

strictNullChecks deep

With strictNullChecks on, null and undefined cannot be assigned to other types. This affects property access, method calls, and return types. Calling .toUpperCase() on a string | null value is a compile error; a null check is required first.

function upper(v: string | null): string {
  if (v === null) return "";
  return v.toUpperCase();  // string
}

function bad(v: string | null): string {
  return v.toUpperCase();  // error: v may be null
}

Flow analysis

TypeScript performs flow analysis to determine whether a variable is null at a point. After a null check in an if condition, the variable is narrowed to non-null type in the subsequent code. This provides safe access.

function len(v: string | null): number {
  if (v !== null) {
    return v.length;  // string
  }
  return 0;
}

Practice Handle nullable with strictNullChecks

Write an upper(v: string | null): string function. If v === null, return ""; otherwise return v.toUpperCase(). Print results via console.log(upper("hello")) and console.log(upper(null)).

Starter code

index.ts
// upper fonksiyonunu nullable string parametreyle yaz

// null ise boş dize, değilse toUpperCase döndür

// upper("hello") ve upper(null) sonuçlarını yazdır

Sample solution

index.ts
function upper(v: string | null): string {
  if (v === null) {
    return "";
  }
  return v.toUpperCase();
}

console.log(upper("hello"));
console.log(upper(null));

Expected output

HELLO

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens when a method is called directly on a value of type string | null with strictNullChecks on?

  • The value becomes undefined
  • Compile error: a null check is required first Correct answer
  • Runtime error
  • The method is called automatically

Explanation: strictNullChecks considers the null possibility; calling .toUpperCase() on a string | null value is a compile error because null has no method.

2 Narrowing with null check

Question
function len(v: string | null): number {
  if (v !== ____) {
    return v.length;
  }
  return 0;
}
Answer
function len(v: string | null): number {
  if (v !== null) {
    return v.length;
  }
  return 0;
}

Explanation: The v !== null check narrows v to string in the condition body; this provides safe access under strictNullChecks.

3 strictNullChecks deep parts

Term Meaning
string | null carries null possibility
if (v === null) separates null branch
v.toUpperCase() safe if not null
akış analizi enables narrowing

All lessons in Advanced