Bird
Raised Fist0
Typescriptprogramming~10 mins

Strict null checks and safety in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Strict null checks and safety
Start
↓
Declare variable with type
↓
Assign value?
↓
Check for null/undefined
↓
Use variable safely
↓
End
This flow shows how TypeScript checks variables for null or undefined when strict null checks are enabled, preventing unsafe use.
Execution Sample
Typescript
let name: string | null = null;
if (name !== null) {
  console.log(name.length);
}
This code declares a variable that can be a string or null, then safely uses it only if it is not null.
Execution Table
StepVariable 'name'Condition 'name !== null'ActionOutput
1nullnull !== null → falseSkip console.log
2name assigned 'Alice''Alice' !== null → trueExecute console.log(name.length)5
3name assigned nullnull !== null → falseSkip console.log
💡 Execution stops after checking condition and either running or skipping the console.log.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
namenullnull'Alice'null
Key Moments - 3 Insights
Why does TypeScript give an error if I try to use 'name.length' without checking for null?
Because with strict null checks on, TypeScript knows 'name' can be null, so accessing 'length' directly might cause a runtime error. See execution_table step 1 where condition is false and console.log is skipped.
What happens if I assign 'null' to a variable typed as 'string' without '| null'?
TypeScript will give a compile-time error because 'null' is not allowed unless the type explicitly includes it. This safety prevents unexpected null values.
How does the condition 'name !== null' help in safe usage?
It narrows the type from 'string | null' to just 'string' inside the if block, so TypeScript allows accessing string properties safely, as shown in execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
Aundefined
Bnull
C5
DError
💡 Hint
Check the 'Output' column in execution_table row for step 2.
At which step does the condition 'name !== null' evaluate to false?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Condition' column in execution_table for steps where 'name' is null.
If 'strictNullChecks' was off, what would happen when accessing 'name.length' without a check?
ATypeScript would allow it without error
BTypeScript would give an error
CThe program would crash at runtime
DThe variable 'name' would become undefined
💡 Hint
Strict null checks control whether TypeScript enforces null safety at compile time.
Concept Snapshot
Strict null checks in TypeScript prevent using variables that might be null or undefined without checking.
Use union types like 'string | null' to allow null.
Always check variables before use (e.g., 'if (name !== null)').
This avoids runtime errors and makes code safer.
Without strict null checks, TypeScript allows unsafe access.
Full Transcript
This visual execution shows how TypeScript's strict null checks work. We start by declaring a variable 'name' that can be a string or null. When we check if 'name !== null', TypeScript knows it's safe to use 'name.length'. If 'name' is null, the code inside the if block is skipped, preventing errors. This safety feature helps catch mistakes early. The execution table traces each step, showing variable values, condition results, and outputs. Key moments explain why checks are needed and how TypeScript enforces them. The quiz tests understanding of these steps and the effect of strict null checks.

Practice

(1/5)
1.

What does enabling strictNullChecks in TypeScript do?

easy
A. It allows assigning null to any type without errors.
B. It automatically converts all null values to empty strings.
C. It disables type checking for null and undefined.
D. It forces you to explicitly handle null and undefined values.

Solution

  1. Step 1: Understand strictNullChecks purpose

    Enabling strictNullChecks makes TypeScript require explicit handling of null and undefined values to avoid runtime errors.
  2. Step 2: Analyze options

    Only It forces you to explicitly handle null and undefined values. correctly describes this behavior. Options B, C, and D are incorrect because they describe behaviors that strictNullChecks does not do.
  3. Final Answer:

    It forces you to explicitly handle null and undefined values. -> Option D
  4. Quick Check:

    strictNullChecks = explicit null handling [OK]
Hint: Remember: strictNullChecks means no silent nulls [OK]
Common Mistakes:
  • Thinking nulls are automatically converted
  • Assuming null checks are disabled
  • Believing null can be assigned anywhere
2.

Which of the following is the correct way to check for null or undefined before accessing a variable value in TypeScript with strictNullChecks enabled?

let value: string | null | undefined;
easy
A. if (value !== null && value !== undefined) { console.log(value.length); }
B. if (value) { console.log(value.length); }
C. console.log(value.length);
D. if (value == null) { console.log(value.length); }

Solution

  1. Step 1: Understand null and undefined checks

    With strictNullChecks, you must check both null and undefined explicitly before accessing properties.
  2. Step 2: Evaluate each option

    if (value !== null && value !== undefined) { console.log(value.length); } correctly checks both null and undefined. if (value) { console.log(value.length); } may fail if value is an empty string. console.log(value.length); causes an error. if (value == null) { console.log(value.length); } checks for null but then accesses length inside the if, which is incorrect logic.
  3. Final Answer:

    if (value !== null && value !== undefined) { console.log(value.length); } -> Option A
  4. Quick Check:

    Check both null and undefined explicitly [OK]
Hint: Use !== null && !== undefined to be safe [OK]
Common Mistakes:
  • Using only if(value) which fails on empty strings
  • Accessing properties without checks
  • Using == null but then accessing inside that block
3.

What will be the output of the following TypeScript code with strictNullChecks enabled?

function greet(name: string | null) {
  if (name === null) {
    return "Hello, guest!";
  }
  return `Hello, ${name.toUpperCase()}!`;
}

console.log(greet(null));
console.log(greet("alice"));
medium
A. "Hello, null!" and "Hello, ALICE!"
B. "Hello, guest!" and "Hello, ALICE!"
C. Compilation error due to missing null check
D. Runtime error on null input

Solution

  1. Step 1: Analyze null check in function

    The function checks if name === null and returns "Hello, guest!" in that case, so it safely handles null.
  2. Step 2: Check outputs for calls

    Calling greet(null) returns "Hello, guest!". Calling greet("alice") returns "Hello, ALICE!" because toUpperCase() is called on a string.
  3. Final Answer:

    "Hello, guest!" and "Hello, ALICE!" -> Option B
  4. Quick Check:

    Null check prevents errors, outputs as expected [OK]
Hint: Check null before using string methods [OK]
Common Mistakes:
  • Expecting runtime error on null
  • Thinking compilation error occurs
  • Ignoring null check and causing error
4.

Identify the error in this TypeScript code with strictNullChecks enabled and suggest a fix:

function printLength(text: string | null) {
  console.log(text.length);
}
medium
A. Error: Object is possibly 'null'. Fix: Add a null check before accessing length.
B. Error: Missing return type. Fix: Add : void to function.
C. Error: text should be string only. Fix: Remove null from type.
D. No error. Code is correct.

Solution

  1. Step 1: Identify the error

    Accessing text.length without checking if text is null causes a compile error under strictNullChecks.
  2. Step 2: Suggest fix

    Add a check like if (text !== null) before accessing length to ensure safety.
  3. Final Answer:

    Error: Object is possibly 'null'. Fix: Add a null check before accessing length. -> Option A
  4. Quick Check:

    Always check null before property access [OK]
Hint: Add null checks before property access [OK]
Common Mistakes:
  • Ignoring null check and expecting no error
  • Changing type instead of fixing code
  • Thinking return type causes error
5.

Given this TypeScript function with strictNullChecks enabled, which modification safely handles undefined and null inputs without errors?

function formatName(name: string | null | undefined) {
  return name.toUpperCase();
}
hard
A. Use non-null assertion: return name!.toUpperCase();
B. Change parameter type to string only and remove null and undefined.
C. Add a check: if (name == null) return "Unknown"; before calling toUpperCase().
D. Remove strictNullChecks from tsconfig.

Solution

  1. Step 1: Identify unsafe code

    Calling toUpperCase() on name without checking for null or undefined causes errors with strictNullChecks.
  2. Step 2: Evaluate options for safety

    Add a check: if (name == null) return "Unknown"; before calling toUpperCase(). adds a check for both null and undefined (using == null) and returns a default string, safely avoiding errors. Change parameter type to string only and remove null and undefined. removes null safety but is less flexible. Use non-null assertion: return name!.toUpperCase(); forces non-null assertion which can cause runtime errors. Remove strictNullChecks from tsconfig. disables safety feature, not recommended.
  3. Final Answer:

    Add a check: if (name == null) return "Unknown"; before calling toUpperCase(). -> Option C
  4. Quick Check:

    Check null/undefined before method calls [OK]
Hint: Use if(name == null) to check null and undefined together [OK]
Common Mistakes:
  • Using non-null assertion unsafely
  • Removing null from type instead of checking
  • Disabling strictNullChecks instead of fixing code
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard