Practice & Assessment
Test your understanding of Functions and Type Narrowing
Multiple Choice Questions
5What is the return type of a function that never returns a value?
In a function overload, what must be true of the implementation signature?
Which narrowing approach works best for distinguishing between two interfaces that share no common methods?
What does a function returning value is string as its return type mean?
Why should you avoid using the uppercase Function type in TypeScript?
Coding Challenges
1Build a type-safe event emitter
Create a typed EventEmitter class. Define a type EventMap as a Record mapping event name strings to their payload types. Implement on(event, handler) that registers a callback, emit(event, payload) that calls all registered handlers, and off(event, handler) that removes a specific handler. The handlers array must be typed correctly so that handlers for a given event name receive the correct payload type. Test it with at least two events: 'login' with payload { userId: string } and 'error' with payload { message: string }. Estimated time: 25 minutes.
Mini Project
Typed Form Validator
Build a form validation library. Define a Validator<T> type as a function (value: T) => string | null — returning null means valid, returning a string gives the error message. Create at least five validators: required (rejects empty string), minLength(n) (returns a Validator<string>), maxLength(n), isEmail (regex check), and isPositive (Validator<number>). Implement a validate<T>(value: T, validators: Validator<T>[]) function that runs all validators and returns the first error string or null. Then create a typed form schema as a Record mapping field names to their validators, and a validateForm function that runs each field through its validators and returns a Record of field names to error strings. Demonstrate with a user registration form: username, email, age fields.
