Bird
Raised Fist0
Typescriptprogramming~20 mins

Truthiness narrowing in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Truthiness Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of truthiness narrowing with && operator
What is the output of the following TypeScript code?
Typescript
function checkValue(val: string | null) {
  if (val && val.length > 3) {
    return val.toUpperCase();
  }
  return "Too short or null";
}

console.log(checkValue("test"));
console.log(checkValue("no"));
console.log(checkValue(null));
A"TEST"\n"Too short or null"\n"Too short or null"
B"TEST"\n"Too short or null"\n"null"
C"TEST"\n"no"\n"Too short or null"
D"test"\n"no"\n"null"
Attempts:
2 left
💡 Hint
Remember that && checks if the first value is truthy before evaluating the second.
❓ Predict Output
intermediate
2:00remaining
Output of truthiness narrowing with if statement
What will be printed by this TypeScript code?
Typescript
function printLength(str?: string | null) {
  if (str) {
    console.log(str.length);
  } else {
    console.log("No string");
  }
}

printLength("");
printLength("hello");
printLength(null);
A0\nNo string\nNo string
BNo string\n5\nNo string
C0\n5\nNo string
DNo string\nNo string\nNo string
Attempts:
2 left
💡 Hint
Empty string is falsy in JavaScript/TypeScript.
🔧 Debug
advanced
2:00remaining
Identify the error in truthiness narrowing
What error will this TypeScript code produce when compiled or run?
Typescript
function getFirstChar(s: string | null) {
  if (s === null || s.length === 0) {
    return "Empty";
  }
  return s[0];
}

console.log(getFirstChar(null));
AReturns 'Empty' without error
BType error: s might be null when accessing s[0]
CSyntax error: missing colon
DRuntime error: Cannot read property 'length' of null
Attempts:
2 left
💡 Hint
Logical OR (||) short-circuits: if the left side is truthy, the right side is not evaluated.
📝 Syntax
advanced
2:00remaining
Which option correctly narrows a union type using truthiness?
Which of the following TypeScript snippets correctly narrows the variable 'input' of type string | undefined using truthiness?
Aif (input !== undefined && input.length > 0) { console.log(input); }
Bif (input.length > 0) { console.log(input); }
Cif (input && input.length > 0) { console.log(input); }
Dif (input != null || input.length > 0) { console.log(input); }
Attempts:
2 left
💡 Hint
Check which condition safely narrows input to a string before accessing length.
🚀 Application
expert
2:00remaining
Determine the output count of filtered array using truthiness narrowing
Given this TypeScript code, how many elements will be in the filtered array?
Typescript
const values: (string | null | undefined)[] = ["apple", "", null, "banana", undefined, " "];
const filtered = values.filter(v => v && v.trim().length > 0);
console.log(filtered.length);
A3
B5
C4
D2
Attempts:
2 left
💡 Hint
Remember that empty string and strings with only spaces behave differently with trim().

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