Type checking

3 snippets across 2 stacks - Python, JavaScript

Also written as check type

PYPython

Type Checking at Runtime

PY · Variables & Types
Syntax
type(obj)
isinstance(obj, ClassName)
Example
score = 95.5
print(type(score))
print(isinstance(score, (int, float)))
Output
<class 'float'>
True

Note Prefer isinstance() over type() == because isinstance handles subclasses correctly. The second arg can be a tuple of types.

typing Module Essentials

PY · Common Standard Library
Syntax
from typing import Optional, Union, TypeVar, Generic
Example
from typing import TypeVar, Generic

T = TypeVar("T")

class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()

stack = Stack[int]()
stack.push(42)
print(stack.pop())
Output
42

Note Since 3.10, use X | Y instead of Union[X, Y]. Since 3.12, use the type parameter syntax: class Stack[T]: instead of TypeVar + Generic.

JSJavaScript

typeof Operator

JS · Data Types
Syntax
typeof value
Example
console.log(typeof "hello");    // "string"
console.log(typeof 42);         // "number"
console.log(typeof true);       // "boolean"
console.log(typeof undefined);  // "undefined"
console.log(typeof null);       // "object" (!)  
console.log(typeof []);         // "object"
console.log(typeof (() => {})); // "function"

Note typeof null === "object" is a historic bug that will never be fixed. Use value === null for null checks. Arrays report as "object" -- use Array.isArray() instead.

Frequently asked questions

How does Python handle type checking?
This task is covered in 2 stacks on this page: Python, JavaScript. The "Type Checking at Runtime" snippet in Python uses `type(obj)`.
Which code does the Python example use?
The "Type Checking at Runtime" snippet uses `type(obj)`, from the Variables & Types section of the Python cheat sheet.
Which stacks cover "type checking" on this page?
Python, JavaScript. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Type Checking at Runtime": Prefer isinstance() over type() == because isinstance handles subclasses correctly. The second arg can be a tuple of types.