Recall & Review
beginner
What is a type predicate in TypeScript?
A type predicate is a special return type in a function that tells TypeScript the type of a variable when the function returns true. It helps the compiler narrow down types in conditional checks.
Click to reveal answer
beginner
How do you write a type predicate function signature?
You write it as <code>function isType(value: any): value is Type</code>. The <code>value is Type</code> part is the type predicate telling TypeScript what type <code>value</code> has if the function returns true.Click to reveal answer
intermediate
Why use type predicates instead of simple boolean functions?
Type predicates inform TypeScript about the type of a variable after a check, enabling better type safety and autocompletion. Simple boolean functions do not provide this type information.
Click to reveal answer
beginner
Example: What does this function do?<br><pre>function isString(value: unknown): value is string { return typeof value === 'string'; }</pre>This function checks if
value is a string. If it returns true, TypeScript knows value is a string from that point on.Click to reveal answer
intermediate
Can type predicates be used with custom types or interfaces?
Yes! You can write type predicates to check if a value matches a custom interface or type, helping TypeScript narrow complex types in your code.
Click to reveal answer
What does the syntax
value is Type in a function return type mean?✗ Incorrect
The
value is Type syntax is a type predicate telling TypeScript that when the function returns true, value is of type Type.Which of these is a valid type predicate function signature?
✗ Incorrect
Only option C uses the type predicate syntax
value is number to inform TypeScript about the type.What benefit do type predicates provide in TypeScript?
✗ Incorrect
Type predicates help TypeScript understand the type of a variable after a check, improving type safety and developer experience.
Can type predicates be used to check if an object matches a custom interface?
✗ Incorrect
Type predicates can be written to check any type, including custom interfaces or complex types.
What happens if a type predicate function returns false?
✗ Incorrect
If the type predicate returns false, TypeScript knows the variable does not have the specified type.
Explain what a type predicate is and how it helps TypeScript with type checking.
Think about how TypeScript knows the type of a variable after a check.
You got /4 concepts.
Write a simple type predicate function that checks if a value is an array of numbers.
Use 'value is number[]' as the return type and check elements inside the array.
You got /4 concepts.