Recall & Review
beginner
What is the main purpose of conditional types in TypeScript?
Conditional types allow you to choose one type or another based on a condition, similar to an if-else statement but for types. They help create flexible and reusable type logic.
Click to reveal answer
intermediate
How can conditional types replace function overloads?
Instead of writing multiple function signatures (overloads), conditional types let you define a single function with a type that changes based on input types, simplifying code and improving maintainability.Click to reveal answer
beginner
Explain this conditional type: <br>
type Result<T> = T extends string ? number : boolean;This type means: if T is a string, then Result<T> is number; otherwise, Result<T> is boolean. It picks the output type based on whether T is a string.
Click to reveal answer
intermediate
Why might conditional types be preferred over overloads in some cases?
Conditional types reduce repetition by combining multiple overloads into one type expression. This makes code easier to read, write, and maintain, especially when many similar overloads exist.
Click to reveal answer
beginner
What does the 'extends' keyword do in a conditional type?
In conditional types, 'extends' checks if one type fits within another. It acts like a test: if the left type can be assigned to the right type, the condition is true.
Click to reveal answer
What does this conditional type do? <br>
type Check<T> = T extends number ? 'num' : 'not num';✗ Incorrect
The conditional type checks if T is assignable to number. If yes, it returns 'num', otherwise 'not num'.
Which keyword is used to test a type condition in conditional types?
✗ Incorrect
'extends' is used in conditional types to check if one type fits within another.
How do conditional types help replace function overloads?
✗ Incorrect
Conditional types allow one function signature to adapt its return type based on input types, replacing multiple overloads.
What is the output type of
Result<string> if type Result<T> = T extends string ? number : boolean;?✗ Incorrect
Since T is string, the condition is true, so the type is number.
Which is NOT a benefit of using conditional types over overloads?
✗ Incorrect
Conditional types affect compile-time types only and do not improve runtime performance.
Describe how conditional types work and how they can replace function overloads in TypeScript.
Think about how if-else logic applies to types.
You got /4 concepts.
Write a simple conditional type that returns 'string' if the input type is boolean, and 'number' otherwise.
Use T extends boolean ? string : number
You got /3 concepts.