0
0
Typescriptprogramming~5 mins

Truthiness narrowing in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is truthiness narrowing in TypeScript?
Truthiness narrowing is when TypeScript uses checks like if or ! to refine the type of a variable based on whether it is truthy or falsy.
Click to reveal answer
beginner
Which values are considered falsy in JavaScript and TypeScript?
The falsy values are: false, 0, '' (empty string), null, undefined, and NaN. Everything else is truthy.
Click to reveal answer
beginner
How does TypeScript narrow the type of a variable in this code?<br><pre>let value: string | null = getValue();
if (value) {
  // What is the type of value here?
}</pre>
Inside the if (value) block, TypeScript narrows value to string because null is falsy and filtered out.
Click to reveal answer
intermediate
What happens to the type of a variable after a if (!variable) check?
After if (!variable), TypeScript narrows the variable's type to only the falsy types it can be, excluding truthy ones.
Click to reveal answer
beginner
Why is truthiness narrowing useful in TypeScript?
It helps catch errors early by letting TypeScript know when a variable cannot be null or undefined, so you can safely use it without extra checks.
Click to reveal answer
Which of these values is truthy in TypeScript?
A"hello"
B"" (empty string)
Cnull
D0
Given let x: string | null;, what is the type of x inside if (x) block?
Astring | null
Bstring
Cnull
Dnever
What does if (!value) check for in TypeScript?
Avalue is falsy
Bvalue is a string
Cvalue is truthy
Dvalue is a number
Which of these is NOT a falsy value in TypeScript?
Aundefined
BNaN
C"false" (string)
D0
Why does TypeScript use truthiness narrowing?
ATo convert all variables to boolean
BTo make variables immutable
CTo remove all null values from code
DTo help safely use variables by refining their types based on runtime checks
Explain how TypeScript uses truthiness narrowing to refine variable types in conditional statements.
Think about how an if statement filters out falsy values.
You got /4 concepts.
    List the common falsy values in TypeScript and explain why knowing them helps with truthiness narrowing.
    Recall the basic falsy values from JavaScript.
    You got /3 concepts.