Lesson 24 of 55
15 mins readPython Assertion Signatures
In Plain English
Assertion functions throw an error if a given condition is false. The `asserts value is Type` signature informs TypeScript that the variable is guaranteed to be that type for the remainder of the scope.
Core Rules to Remember

asserts condition: Eliminates null/undefined or narrows types across subsequent scope after execution.

Fail Fast: Throws descriptive errors immediately if preconditions fail.
Live Interactive Example
Hit Run Code to see it liveAsserting Type Invariants
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
Output Console
Click "Run Code" to view the rendered output.
How it works: After assertIsDefined executes, TypeScript eliminates null and undefined from rawPayload for the rest of the scope.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Assert Number Value
Write function assertIsNumber(val: unknown): asserts val is number that throws new Error("Not a number") if typeof val !== "number".
Test by asserting a variable num: unknown = 42, then print (num * 2).
1
2
3
4
5
6
7
8
9
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.