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.