Module lessons (1/2)
Type Guards
Write safe custom predicates (x is Type) and assertion functions (asserts x is Type).
What you'll learn in this lesson
- Understand why a plain boolean helper function (
: boolean) doesn't restrict the type in the caller. - Write custom Type Predicate (
function isAdmin(u: User): u is Admin) to propagate the narrowing. - Combine
typeof, control!== null, and operatorininto guards onunknownvalues. - Use Assertion Functions (
asserts val is T) to validate input invariants with immediate error throwing.
Overview
So far you have used inline guards like typeof or in directly inside if. When the same control logic is abstracted into a separate function, TypeScript loses track of the restriction unless the function explicitly declares a type predicate in its signature.
The syntax : parametro is TipoRistretto informs the compiler: _if this function returns true, then in the scope of the caller the variable is definitely TipoRistretto_.
Sections covered in this lesson
- 1Custom Type Predicates (
x is Tipo) - 2Validate
unknownobjects and Assertion Functions - 3Guided practice
- 4Check for understanding
Unlock "Type Guards" and the full Course TypeScript curriculum
Write safe custom predicates (x is Type) and assertion functions (asserts x is Type).
Unlock all 6 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course TypeScript plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.