Lesson 21 of 55
15 mins readPython Narrowing with instanceof and the in Operator
In Plain English
When dealing with class instances or disparate object shapes, instanceof and the in keyword enable precise runtime branch narrowing.
Core Rules to Remember

instanceof: Checks the prototype chain of an object against constructor functions.

in Operator: "prop" in obj checks for property presence and narrows union objects.
Live Interactive Example
Hit Run Code to see it liveGuarding with instanceof and in
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
26
Output Console
Click "Run Code" to view the rendered output.
How it works: instanceof checks prototype inheritance, and "code" in err validates property existence safely.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Narrow Audio vs Video Stream
Define type AudioStream = { bitrate: number; channels: number }.
Define type VideoStream = { bitrate: number; resolution: string }.
Write function getStreamInfo(s: AudioStream | VideoStream): string that returns `Video: ${s.resolution}` if "resolution" in s, else `Audio: ${s.channels}ch`.
Call getStreamInfo({ bitrate: 128, channels: 2 }) and print.
1
2
3
4
5
6
7
8
9
10
11
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.