Recall & Review
beginner
What is runtime type checking in TypeScript?
Runtime type checking means verifying the type of a value while the program is running, not just during compilation. It helps catch errors when data comes from outside sources like user input or APIs.
Click to reveal answer
beginner
Name two common strategies for runtime type checking in TypeScript.
1. Using
typeof and instanceof operators.<br>2. Using custom type guard functions that check object shapes.Click to reveal answer
intermediate
How does a custom type guard function work?
A custom type guard is a function that returns a boolean and uses the
is keyword to tell TypeScript the type of a value if the function returns true. It checks properties or structure at runtime.Click to reveal answer
beginner
What is a limitation of using
typeof for runtime type checking?typeof only works well for primitive types like string, number, and boolean. It cannot check complex objects or arrays accurately.Click to reveal answer
intermediate
Why might you use a library like
zod or io-ts for runtime type checking?These libraries provide schemas to define expected data shapes and validate data at runtime easily. They help ensure data matches types and give clear error messages when it doesn't.
Click to reveal answer
Which operator is best for checking if a value is a string at runtime in TypeScript?
✗ Incorrect
The
typeof operator returns 'string' for string values, making it suitable for checking primitive types like strings.What does a custom type guard function return to inform TypeScript about a type?
✗ Incorrect
Custom type guards return a boolean and use a type predicate like
value is Type to tell TypeScript the type when true.Which runtime type checking method can verify the shape of an object?
✗ Incorrect
Custom type guard functions can check object properties to verify the shape and type at runtime.
Why is
instanceof not always reliable for runtime type checking?✗ Incorrect
instanceof checks if an object is an instance of a class or constructor function, so it doesn't work well with plain objects or interfaces.What advantage do libraries like
zod provide for runtime type checking?✗ Incorrect
Libraries like
zod help define schemas and validate data easily at runtime, giving clear feedback when data doesn't match expected types.Explain how you would create a custom type guard function in TypeScript to check if a value is a specific object type.
Think about a function that tests properties and tells TypeScript the type when true.
You got /4 concepts.
Describe the differences between using 'typeof', 'instanceof', and custom type guards for runtime type checking.
Consider what each method can and cannot check at runtime.
You got /4 concepts.