Type Checking
Object Type
Programming
Data Validation
Code Verification

How to check if an object is a certain type

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Checking an object's type at runtime is a common task across programming languages. Python uses isinstance() and type(), JavaScript uses typeof and instanceof, C# uses is and as, and Java uses instanceof. The recommended approach in most languages is the one that respects inheritance — isinstance() in Python, instanceof in JavaScript/Java, and is in C# — because they return true for both the exact class and its subclasses.

Python

python
1x = 42
2print(isinstance(x, int))        # True
3print(isinstance(x, (int, float)))  # True — checks multiple types
4
5name = "Alice"
6print(isinstance(name, str))      # True
7
8items = [1, 2, 3]
9print(isinstance(items, list))    # True
10print(isinstance(items, (list, tuple)))  # True

isinstance() respects inheritance:

python
1class Animal:
2    pass
3
4class Dog(Animal):
5    pass
6
7rex = Dog()
8print(isinstance(rex, Dog))     # True
9print(isinstance(rex, Animal))  # True — Dog IS an Animal

type() for Exact Type Match

python
1rex = Dog()
2print(type(rex) is Dog)     # True
3print(type(rex) is Animal)  # False — type() ignores inheritance
4
5# type() returns the class object
6print(type(42))        # <class 'int'>
7print(type("hello"))   # <class 'str'>
8print(type([1, 2]))    # <class 'list'>

Use type() only when you need to distinguish between a parent and child class. In most cases, isinstance() is the better choice.

JavaScript

typeof for Primitives

javascript
1console.log(typeof 42);          // "number"
2console.log(typeof "hello");     // "string"
3console.log(typeof true);        // "boolean"
4console.log(typeof undefined);   // "undefined"
5console.log(typeof null);        // "object" — historical bug!
6console.log(typeof [1, 2]);      // "object" — arrays are objects
7console.log(typeof {});          // "object"
8console.log(typeof function(){}); // "function"

instanceof for Objects and Classes

javascript
1class Animal {}
2class Dog extends Animal {}
3
4const rex = new Dog();
5console.log(rex instanceof Dog);    // true
6console.log(rex instanceof Animal); // true — respects inheritance
7
8console.log([] instanceof Array);   // true
9console.log([] instanceof Object);  // true
10
11// Check arrays specifically
12console.log(Array.isArray([1, 2]));   // true — most reliable for arrays
13console.log(Array.isArray("hello"));  // false

Constructor Check

javascript
const date = new Date();
console.log(date.constructor === Date);  // true
console.log(date.constructor.name);      // "Date"

C#

csharp
1object value = 42;
2
3if (value is int)
4    Console.WriteLine("It's an integer");
5
6if (value is int number)
7    Console.WriteLine($"Integer value: {number}");  // Pattern matching
8
9// Check against multiple types
10if (value is int or float or double)
11    Console.WriteLine("It's a number");

as Keyword for Safe Casting

csharp
1object obj = "Hello";
2
3string text = obj as string;  // Returns null if cast fails
4if (text != null)
5    Console.WriteLine(text.Length);
6
7// Equivalent pattern matching (cleaner)
8if (obj is string s)
9    Console.WriteLine(s.Length);

GetType() for Exact Type

csharp
1object value = 42;
2
3Console.WriteLine(value.GetType());           // System.Int32
4Console.WriteLine(value.GetType() == typeof(int));  // True
5Console.WriteLine(value.GetType().Name);      // "Int32"

Java

instanceof

java
1Object value = "Hello";
2
3if (value instanceof String) {
4    System.out.println("It's a string");
5}
6
7// Pattern matching (Java 16+)
8if (value instanceof String s) {
9    System.out.println("Length: " + s.length());
10}
11
12// Inheritance
13class Animal {}
14class Dog extends Animal {}
15
16Animal rex = new Dog();
17System.out.println(rex instanceof Dog);    // true
18System.out.println(rex instanceof Animal); // true

getClass() for Exact Type

java
1Object value = 42;
2System.out.println(value.getClass());               // class java.lang.Integer
3System.out.println(value.getClass() == Integer.class); // true
4System.out.println(value.getClass().getSimpleName()); // "Integer"

TypeScript

typescript
1// typeof for primitives (same as JavaScript)
2const x: unknown = 42;
3if (typeof x === "number") {
4    console.log(x.toFixed(2));  // TypeScript narrows the type
5}
6
7// instanceof for classes
8class Dog {
9    bark() { console.log("Woof"); }
10}
11
12const animal: unknown = new Dog();
13if (animal instanceof Dog) {
14    animal.bark();  // TypeScript knows it's a Dog
15}
16
17// Type guards for interfaces
18interface Cat {
19    meow(): void;
20}
21
22function isCat(obj: any): obj is Cat {
23    return typeof obj.meow === "function";
24}
25
26if (isCat(animal)) {
27    animal.meow();
28}

Common Pitfalls

  • JavaScript typeof null === "object": This is a long-standing bug in JavaScript. Check for null explicitly with value === null before using typeof.
  • Using type() instead of isinstance() in Python: type(obj) is SomeClass fails for subclasses. Unless you need exact type matching, always use isinstance() which respects inheritance.
  • JavaScript typeof for arrays and objects: typeof [] returns "object", not "array". Use Array.isArray() to check for arrays specifically.
  • Forgetting that instanceof does not work across iframes in JavaScript: Each iframe has its own global scope. An array created in one iframe is not an instanceof Array from another iframe. Use Array.isArray() which works cross-realm.
  • Overusing type checks instead of polymorphism: If you find yourself writing long if/elif chains checking types, consider using polymorphism (method overriding) or the visitor pattern instead. Type checks are a code smell when used to dispatch behavior.

Summary

LanguageCheck with inheritanceExact type checkPrimitive check
Pythonisinstance(obj, Type)type(obj) is Typeisinstance(obj, int)
JavaScriptobj instanceof Classobj.constructor === Classtypeof obj === "number"
C#obj is Typeobj.GetType() == typeof(Type)obj is int
Javaobj instanceof Typeobj.getClass() == Type.classobj instanceof Integer
TypeScriptobj instanceof ClassN/Atypeof obj === "string"
  • Prefer inheritance-aware checks (isinstance, instanceof, is) over exact type checks in most scenarios
  • Use exact type checks only when you need to distinguish between a parent and child class

Course illustration
Course illustration

All Rights Reserved.