Bird
Raised Fist0
Typescriptprogramming~10 mins

Truthiness narrowing in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Truthiness narrowing
Start with variable of type: string | null | undefined
↓
Check if variable is truthy
↓
Variable narrowed to string
↓
Use variable as string
↓
End
Start with a variable that can be string, null, or undefined. Check if it is truthy to narrow its type to string. Otherwise, handle falsy cases including null or undefined.
Execution Sample
Typescript
function greet(name: string | null | undefined) {
  if (name) {
    console.log(`Hello, ${name.toUpperCase()}`);
  } else {
    console.log("Hello, guest");
  }
}
This code checks if 'name' is truthy to safely use it as a string; otherwise, it greets a guest.
Execution Table
StepVariable 'name'Condition 'if(name)'Type Narrowed ToActionOutput
1"Alice"truestringExecute if blockHello, ALICE
2nullfalsestring | null | undefinedExecute else blockHello, guest
3undefinedfalsestring | null | undefinedExecute else blockHello, guest
4""falsestring | null | undefinedExecute else blockHello, guest
Exit---End of function-
💡 Execution stops after handling all cases of 'name' with truthiness check.
Variable Tracker
Variable 'name'StartAfter Step 1After Step 2After Step 3After Step 4Final
name"Alice" / null / undefined / """Alice"nullundefined""varies per call
Key Moments - 3 Insights
Why does an empty string ('') cause the else block to run even though it's a string?
Because '' is falsy in JavaScript/TypeScript, so the condition 'if(name)' is false, taking the else branch (type still string | null | undefined), as shown in execution_table row 4.
How does the type narrow from 'string | null | undefined' to just 'string' inside the if block?
The condition 'if(name)' checks truthiness, so inside the if block TypeScript knows 'name' cannot be null or undefined, narrowing it to 'string' as shown in execution_table row 1.
What happens if we try to use 'name.toUpperCase()' without the if check?
It would cause a runtime error if 'name' is null or undefined, but the if check prevents this by ensuring 'name' is truthy before calling 'toUpperCase()', as shown in the code and execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the type of 'name' inside the if block when 'name' is "Alice"?
Aundefined
Bstring
Cnull
Dstring | null | undefined
💡 Hint
Check execution_table row 1 under 'Type Narrowed To' column.
At which step does the condition 'if(name)' evaluate to false?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Condition' column in execution_table rows 2, 3, and 4.
If we remove the if check, what is the risk when 'name' is null?
ATypeScript will automatically fix it
BNo risk, code runs fine
CRuntime error when calling toUpperCase()
DOutput will be 'Hello, guest'
💡 Hint
Refer to key_moments explanation about using 'name.toUpperCase()' without checking.
Concept Snapshot
Truthiness narrowing in TypeScript:
- Use 'if(variable)' to check if variable is truthy
- Narrows type from 'T | null | undefined' to 'T'
- Prevents runtime errors by ensuring variable is not null/undefined
- Falsy values: null, undefined, '', 0, false
- Use else block to handle falsy cases safely
Full Transcript
This example shows how TypeScript uses truthiness narrowing to safely work with variables that can be string, null, or undefined. The function greet takes a variable 'name' which might be a string or null or undefined. The if statement checks if 'name' is truthy. If yes, TypeScript narrows the type to string, so we can safely call toUpperCase() on it. If not, the else block runs, greeting a guest. The execution table shows different inputs and how the condition evaluates, what type narrowing happens, and what output is produced. Key moments clarify why empty string is falsy and how narrowing prevents errors. The quiz tests understanding of type narrowing and truthiness checks. This helps beginners see how TypeScript uses runtime checks to narrow types and avoid errors.

Practice

(1/5)
1. What does truthiness narrowing in TypeScript help you do inside an if statement?
easy
A. It forces TypeScript to ignore type errors.
B. It converts all values to strings automatically.
C. It tells TypeScript the value is not null, undefined, or falsy, so you can use it safely.
D. It makes the code run faster by skipping checks.

Solution

  1. Step 1: Understand what truthiness means

    Truthiness means a value is considered true in a boolean context, so it is not null, undefined, 0, empty string, or false.
  2. Step 2: Apply truthiness narrowing in TypeScript

    Inside an if statement, TypeScript narrows the type by excluding falsy values, letting you safely use the value without extra checks.
  3. Final Answer:

    It tells TypeScript the value is not null, undefined, or falsy, so you can use it safely. -> Option C
  4. Quick Check:

    Truthiness narrowing = safe value use [OK]
Hint: If inside if(value), value is truthy and safe to use [OK]
Common Mistakes:
  • Thinking it converts values to strings
  • Believing it skips type checks
  • Assuming it improves runtime speed
2. Which of the following TypeScript if statements correctly uses truthiness narrowing?
easy
A. if (value == false) { console.log(value); }
B. if (value === 0) { console.log(value); }
C. if (value = true) { console.log(value); }
D. if (value !== null && value !== undefined) { console.log(value); }

Solution

  1. Step 1: Check each if condition for truthiness narrowing

    if (value !== null && value !== undefined) { console.log(value); } explicitly checks for not null and not undefined, which is a common way to narrow truthy values.
  2. Step 2: Identify incorrect syntax or logic

    if (value == false) { console.log(value); } checks if value is false (falsy), which is opposite of truthiness narrowing. if (value = true) { console.log(value); } uses assignment (=) instead of comparison (===). if (value === 0) { console.log(value); } checks if value equals 0, which is falsy, so it does not narrow to truthy.
  3. Final Answer:

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

    Correct syntax and logic = if (value !== null && value !== undefined) { console.log(value); } [OK]
Hint: Use !== null && !== undefined for safe truthiness checks [OK]
Common Mistakes:
  • Using assignment (=) instead of comparison (===)
  • Checking for falsy instead of truthy
  • Confusing equality operators
3. What will be the output of this TypeScript code?
function printLength(str?: string) {
  if (str) {
    console.log(str.length);
  } else {
    console.log('No string');
  }
}
printLength('hello');
printLength('');
printLength();
medium
A. 5, No string, No string
B. 5, 0, undefined
C. 5, No string, undefined
D. 5, 0, No string

Solution

  1. Step 1: Analyze the if condition with truthiness narrowing

    The condition if (str) is true only if str is truthy. An empty string ('') is falsy, so it goes to else.
  2. Step 2: Check each function call output

    printLength('hello') prints 5 because 'hello' is truthy and length is 5.
    printLength('') prints 'No string' because '' is falsy.
    printLength() prints 'No string' because str is undefined (falsy).
  3. Final Answer:

    5, No string, No string -> Option A
  4. Quick Check:

    Falsy empty string triggers else [OK]
Hint: Empty string is falsy, so else block runs [OK]
Common Mistakes:
  • Assuming empty string is truthy
  • Expecting undefined to print length
  • Confusing falsy values with null only
4. Find the error in this TypeScript code using truthiness narrowing:
function process(value: string | null) {
  if (value !== null) {
    console.log(value.toUpperCase());
  } else {
    console.log('No value');
  }
}
process(null);
process(undefined);
medium
A. The if condition should check for undefined as well as null.
B. The code will cause a runtime error when value is undefined.
C. The toUpperCase method is not valid for strings.
D. There is no error; the code works fine.

Solution

  1. Step 1: Check the type of value and condition

    Value can be string or null, but the function is called with undefined, which is not handled.
  2. Step 2: Identify missing check for undefined

    The if condition only excludes null, so if value is undefined, it will cause an error when calling toUpperCase.
  3. Final Answer:

    The if condition should check for undefined as well as null. -> Option A
  4. Quick Check:

    Check all falsy types to avoid errors [OK]
Hint: Check both null and undefined for safe narrowing [OK]
Common Mistakes:
  • Ignoring undefined values
  • Assuming null check covers undefined
  • Not testing all input cases
5. Given this TypeScript code, what is the safest way to narrow the type of input to avoid errors when accessing input.length?
function handleInput(input: string | null | undefined | number) {
  if (/* condition here */) {
    console.log(input.length);
  } else {
    console.log('Invalid input');
  }
}
hard
A. if (input) { console.log(input.length); }
B. if (typeof input === 'string' && input) { console.log(input.length); }
C. if (input !== null) { console.log(input.length); }
D. if (input != undefined) { console.log(input.length); }

Solution

  1. Step 1: Identify all possible types of input

    Input can be string, null, undefined, or number. Only strings have a length property.
  2. Step 2: Narrow input to string and check truthiness

    Using typeof input === 'string' ensures input is a string type. Adding && input excludes empty strings (falsy) if needed.
  3. Final Answer:

    if (typeof input === 'string' && input) { console.log(input.length); } -> Option B
  4. Quick Check:

    Check type and truthiness for safe property access [OK]
Hint: Check type string before accessing length [OK]
Common Mistakes:
  • Only checking truthiness without type
  • Ignoring number type causing errors
  • Assuming null check covers undefined
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