Lesson 23 of 55
15 mins readPython User-Defined Type Guards
In Plain English
When built-in typeof or in checks are not enough, user-defined type guards allow you to create custom functions returning a type predicate `param is Type` that instructs the TypeScript compiler.
Core Rules to Remember

Type Predicates: Functions returning arg is Type act as custom compiler narrowing guards.

Runtime + Compile Safety: Runs standard JavaScript boolean logic at runtime while narrowing types at compile time.
Live Interactive Example
Hit Run Code to see it liveCreating Custom Type Predicates
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Output Console
Click "Run Code" to view the rendered output.
How it works: Inside the if (isAdmin(u1)) branch, u1 is automatically narrowed to AdminUser.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Build a Non-Empty String Guard
Write type guard function isString(val: unknown): val is string that checks typeof val === "string".
Write function printUpper(val: unknown): void that logs val.toUpperCase() if isString(val) is true, else logs "NOT_A_STRING".
Call printUpper("zen") and printUpper(123).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.