0
0
Typescriptprogramming~5 mins

Nullish coalescing with types in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the nullish coalescing operator (??) do in TypeScript?
It returns the right-hand side value only if the left-hand side value is null or undefined; otherwise, it returns the left-hand side value.
Click to reveal answer
intermediate
How does nullish coalescing differ from the logical OR (||) operator?
Nullish coalescing (??) only treats null and undefined as empty, while || treats any falsy value (like 0, '', false) as empty.
Click to reveal answer
intermediate
Given: <pre>let value: string | null = null;<br>let result = value ?? 'default';</pre> What is the type of <code>result</code>?
The type of result is string because if value is null, the default string is used.
Click to reveal answer
intermediate
Can nullish coalescing be chained with other operators in TypeScript? Give an example.
Yes. Example: <pre>let a: string | null = null;<br>let b: string | undefined = undefined;<br>let c = a ?? b ?? 'fallback';</pre> This returns the first defined and non-null value.
Click to reveal answer
beginner
Why is nullish coalescing useful when working with optional or nullable types in TypeScript?
Because it safely provides a default value only when a variable is null or undefined, avoiding unintended fallback for falsy but valid values like 0 or empty string.
Click to reveal answer
What will let x = 0 ?? 5; assign to x?
Anull
B0
Cundefined
D5
Which values cause the right side of ?? to be used?
Anull and undefined
Bfalse and 0
Cempty string and false
Dall falsy values
What is the type of let y: string | undefined = undefined; let z = y ?? 'hello';?
Anever
Bstring | undefined
Cundefined
Dstring
Which operator should you use to provide a default only when a value is null or undefined?
A??
B||
C&&
D!
What will let a = false ?? true; assign to a?
Atrue
Bundefined
Cfalse
Dnull
Explain how the nullish coalescing operator (??) works with nullable types in TypeScript.
Think about when you want to keep 0 or false but still provide a fallback for null or undefined.
You got /3 concepts.
    Describe the difference between using || and ?? when assigning default values in TypeScript.
    Consider what happens if your value is 0 or false.
    You got /3 concepts.