Recall & Review
beginner
What is a custom type guard function in TypeScript?
A custom type guard function is a special function that checks if a value matches a specific type and tells TypeScript about this check, helping it understand the type better during code execution.
Click to reveal answer
beginner
How do you define a custom type guard function signature?
You define it with a return type using the syntax: <code>paramName is Type</code>. For example, <code>function isString(value: any): value is string</code> means the function returns true if <code>value</code> is a string.Click to reveal answer
intermediate
Why use custom type guard functions instead of simple type checks?
Custom type guards help TypeScript narrow down types in complex situations, improving code safety and enabling better autocompletion and error checking.
Click to reveal answer
beginner
Example: What does this function do?<br><pre>function isNumber(value: any): value is number {<br> return typeof value === 'number';<br>}</pre>This function checks if the input
value is a number. If yes, it returns true and tells TypeScript that value is a number from that point on.Click to reveal answer
intermediate
How does TypeScript behave after a custom type guard returns true?
TypeScript narrows the type of the checked variable to the type specified in the guard, allowing safer access to properties or methods of that type.
Click to reveal answer
What is the correct return type for a custom type guard function checking if a value is a string?
✗ Incorrect
The return type for a custom type guard uses the syntax 'value is string' to tell TypeScript about the type narrowing.
Which keyword is used inside a custom type guard function to check the type of a variable?
✗ Incorrect
You can use 'typeof' for primitive types and 'instanceof' for class instances inside custom type guards.
What benefit does a custom type guard provide in TypeScript?
✗ Incorrect
Custom type guards help TypeScript narrow types, improving safety and developer experience.
Which of these is a valid custom type guard function signature?
✗ Incorrect
The signature 'value is any[]' tells TypeScript this function narrows the type to an array.
After a custom type guard returns true, what can you safely do with the variable?
✗ Incorrect
TypeScript knows the variable has the narrowed type, so you can safely use its specific properties or methods.
Explain what a custom type guard function is and how it helps TypeScript.
Think about how TypeScript understands variable types better after the guard.
You got /3 concepts.
Write a simple custom type guard function that checks if a value is an array.
Use Array.isArray to check the value inside the function.
You got /3 concepts.