Programming Search⌘K

Conceptadvanced

Top type

Also called any type, universal type, universal supertype, Object, object, Any, Any?, unknown, interface{}, ⊤.

The top type is a supertype of every type, so a variable of it can hold any value. Java and C# call it Object, Python object, Kotlin Any? and TypeScript unknown.

Applies to
core-languages

Idea

Sometimes code must accept a value of any type: a list that holds numbers and strings, a function that logs whatever it gets, or a field whose type the program learns only when it runs. The top type is the type that every value has. Every other type is a subtype of it, so a value of any type fits in a variable of the top type. The price is that the code knows nothing about such a value, so it must test the real type before it can do more than pass the value on. Python and Java call the top type object and Object.

values: list[object] = [42, "hi", [1, 2], None, len, object]
print(all(isinstance(v, object) for v in values))
print([type(v).__name__ for v in values])
print(int.__mro__, bool.__mro__[-1])


def describe(x: object) -> str:
    # With the type object, code must test the type before it uses the value.
    if isinstance(x, str):
        return x.upper()
    if isinstance(x, int):
        return str(x + 1)
    return repr(x)


print(describe("hi"), describe(41), describe([1]))
print(issubclass(type, object), isinstance(object, object))
Output
True
['int', 'str', 'list', 'NoneType', 'builtin_function_or_method', 'type']
(<class 'int'>, <class 'object'>) <class 'object'>
HI 42 [1]
True True

Every value in the list is an instance of object: a number, a string, a list, None, a function and even a class. The method resolution order of every class ends with object. describe takes an object, so a type checker allows only the operations that every value has, and the function tests the type with isinstance before it calls upper or adds 1.

How it works

A supertype of every type. "In type theory and computer science, type systems include a top, universal, or any type (often represented with the down tack (⊤) symbol), which includes all other types as subtypes"1. "In object-oriented languages, it is often called Object, as it represents all possible objects"1. It is the dual of the bottom type, which is a subtype of every type and has no values.

Two ideas with one name. "In statically-typed languages, there are two different, often confused, concepts when discussing the top type"1. One is a universal base class, the root of the class hierarchy, which objects have when the program runs. The other is a static type to which code can assign any value, such as void* in C or interface{} in Go, that is not the class of any object1.

A universal base class. In Java, "Class Object is the root of the class hierarchy. Every class has Object as a superclass"2. In C#, the object "type is an alias for System.Object in .NET. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from System.Object"3. In Python, object "is the ultimate base class of all other classes"4. In Kotlin, Any is "The root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass"5, but a variable of type Any cannot hold null, so "the top type is kotlin.Any?, a nullable form of kotlin.Any"1.

A static type for any value. In Go, "all types implement the empty interface", and "the predeclared type any is an alias for the empty interface"6. In C and C++, "the void pointer type (void*) can accept any non-function pointer"1, but it does not record the type of the data it points to. C++ and Rust have no root class: "std::any (in C++) and std::any::Any (in Rust) are not actually top types in the type-system, but rather type-erased containers, from which the data is obtained through downcasting"1. The C++ class any "describes a type-safe container for single values of any copy constructible type"7.

Using a value of the top type. The top type has almost no operations, so code must test the type and then cast down. "Languages with runtime typing often provide downcasting to allow discovering a more specific type for an object at runtime"1. In TypeScript, "The unknown type represents any value"8, and the compiler allows an operation on it only after code narrows the type with a test such as typeof. A Rust &dyn Any "has the is and downcast_ref methods, to test if the contained value is of a given type, and to get a reference to the inner value as a type"9.

Top versus any. Some languages have a second type that also accepts every value but turns off the checks. In Python, "A static type checker will treat every type as assignable to Any and Any as assignable to every type"10, so Any is not a top type: it is the dynamic type of gradual typing. The Python documentation puts the difference this way: "Use object to indicate that a value could be any type in a typesafe manner. Use Any to indicate that a value is dynamically typed"10. TypeScript has the same pair, unknown and any8.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaNative
CIdiom
C#Native
JavaScriptIdiom
TypeScriptNativeUnknown is the top type, and the compiler allows operations on it only after narrowing. any also accepts every value, but it turns off the checks. No example file exists.
GoNative
RustStandard library
KotlinNativeAny is the root of the Kotlin class hierarchy, and the nullable Any? is the top type. No example file exists because kotlinc is not installed.
SQLAbsentEach column has a declared type, and SQL has no type that holds a value of any type. No example file exists.
BashDoes not applyEvery value in Bash is a string, so Bash has no hierarchy of types.
PowerShellNativePowerShell values are .NET objects, so a variable of type [object] can hold any value. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no types of values.
CSSDoes not applyCSS has no types of values in this sense.
Regular expressionsDoes not applyA regular expression has no values and no types.
Language Verdict Mechanism
Python native object, the base class of every class; typing.Any is the unchecked dynamic type
JavaScript idiom no static types; most values inherit from Object.prototype, but primitives are not objects
TypeScript native unknown, which needs narrowing before use; any, which turns off checks
Java native Object is the root of the class hierarchy; primitive values must be boxed
Kotlin native Any? is the top type; Any is the root class and excludes null
C# native object, an alias for System.Object; value types are boxed when they become object
Go native any, an alias for interface{}, which every type implements
Rust stdlib no top type; Box<dyn Any> holds a value of a concrete type, and code can downcast it
C idiom void * points to data of any type, but the type is not stored
C++ stdlib no root class; std::any holds a copyable value of any type; void * as in C
Bash n/a every value is a string, so Bash has no hierarchy of types
PowerShell native values are .NET objects, so [object] holds any value
SQL absent each column has a declared type; SQL has no type for a value of any type
Regex n/a a pattern has no values
HTML n/a HTML has no types of values
CSS n/a CSS has no types of values in this sense

Java, C#, Python and Kotlin have a universal base class, so the top type is also the type of an object at run time. Go and TypeScript have a static top type that is not a class. Rust and C++ have no top type in the language and give a library container that stores the type with the value, and C uses void *, which does not store the type.

The example files show these differences. Python shows that a type checker rejects operations on object and accepts them on Any. JavaScript shows that typeof and instanceof Object disagree for primitives. Java shows a List<Object>, boxing and a failed cast. C# shows boxing and pattern matching on object. Go shows any with a type switch and a type assertion. Rust shows Box<dyn Any> and downcast_ref. C shows a void * that the code must cast back to the right type. C++ shows std::any and std::bad_any_cast.

PythonGitHub
from typing import Any


def shout_object(x: object) -> str:
    # A type checker allows upper only after the isinstance test.
    if isinstance(x, str):
        return x.upper()
    return str(x)


def shout_any(x: Any) -> str:
    # A type checker accepts this call, even for a value that has no upper method.
    return x.upper()


print(shout_object("hi"), shout_object(3))
print(shout_any("hi"))
try:
    shout_any(3)
except AttributeError as e:
    print("AttributeError:", e)
Output
HI 3
HI
AttributeError: 'int' object has no attribute 'upper'
  • Verdict: native. object is the base class of every class, so it is the top type, and a type checker allows only the operations that every object has until code narrows the type. Any also accepts every value, but a type checker does not check its uses, so the error in shout_any(3) appears only when the program runs.
#include <any>
#include <iostream>
#include <string>
#include <typeinfo>
#include <vector>

int main() {
    std::vector<std::any> values{42, std::string("hi"), 3.5};
    for (const auto& v : values) {
        if (const int* n = std::any_cast<int>(&v)) {
            std::cout << "int " << *n + 1 << "\n";
        } else if (const auto* s = std::any_cast<std::string>(&v)) {
            std::cout << "string " << *s << "\n";
        } else {
            std::cout << "other " << (v.type() == typeid(double)) << "\n";
        }
    }

    std::any a = 7;
    try {
        std::cout << std::any_cast<std::string>(a) << "\n";
    } catch (const std::bad_any_cast&) {
        std::cout << "bad_any_cast\n";
    }
    a = std::string("text");
    std::cout << std::any_cast<std::string>(a) << " " << a.has_value() << "\n";
}
Output
int 43
string hi
other 1
bad_any_cast
text 1
  • Verdict: stdlib. C++ has no root class. std::any holds one value of any copyable type and stores its type, so any_cast to a pointer returns nullptr for the wrong type, and any_cast to a value throws std::bad_any_cast. type() gives the stored type. A std::any can take a value of another type later.
JavaGitHub
import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Object> values = new ArrayList<>();
    values.add(42); // boxed to Integer
    values.add("hi");
    values.add(new int[] {1, 2});
    values.add(new StringBuilder("sb"));
    for (Object v : values) {
      System.out.println(v.getClass().getSimpleName());
    }

    Object o = values.get(0);
    if (o instanceof Integer n) {
      System.out.println(n + 1);
    }
    try {
      String s = (String) o;
      System.out.println(s);
    } catch (ClassCastException e) {
      System.out.println("ClassCastException");
    }
    System.out.println(Object.class.getSuperclass() + " " + String.class.getSuperclass().getName());
  }
}
Output
Integer
String
int[]
StringBuilder
43
ClassCastException
null java.lang.Object
  • Verdict: native. Object is the root of the class hierarchy, so a List<Object> can hold a string, an array and a builder. An int is not an object, so add(42) boxes it to an Integer. instanceof with a pattern tests the type and casts in one step, and a plain cast to the wrong type throws ClassCastException. Object has no superclass.
#include <stdio.h>
#include <string.h>

enum kind { INT, TEXT };

/* A void * can point to data of any type, but the type is not stored with it. */
struct box {
    enum kind kind;
    void *data;
};

static void show(struct box b) {
    if (b.kind == INT) {
        printf("int %d\n", *(int *)b.data);
    } else {
        printf("text %s\n", (char *)b.data);
    }
}

int main(void) {
    int n = 42;
    char text[] = "hi";
    struct box items[] = {{INT, &n}, {TEXT, text}};
    for (size_t i = 0; i < sizeof items / sizeof items[0]; i++) {
        show(items[i]);
    }

    /* memcpy takes void * parameters, so it works on objects of any type. */
    double a = 2.5;
    double b = 0;
    memcpy(&b, &a, sizeof a);
    printf("%.1f\n", b);
    return 0;
}
Output
int 42
text hi
2.5
  • Verdict: idiom. C has no top type, but a void * can point to an object of any type. The pointer does not record that type, so struct box stores a tag next to it, and show casts the pointer back by the tag. A wrong tag would make the cast wrong, and C would not detect it. Library functions such as memcpy take void * so that they work on any object.
using System;
using System.Collections.Generic;

var values = new List<object> { 42, "hi", 3.5, new[] { 1, 2 }, DateTime.UnixEpoch };
foreach (object v in values)
{
    Console.WriteLine(v switch
    {
        int n => $"int {n + 1}",
        string s => $"string {s.ToUpper()}",
        double d => $"double {d * 2}",
        int[] a => $"int[] {a.Length}",
        _ => v.GetType().Name,
    });
}

// Boxing copies the value, so a change to i does not change the boxed copy.
int i = 1;
object boxed = i;
i = 2;
Console.WriteLine($"{i} {boxed} {typeof(int).BaseType} {typeof(ValueType).BaseType}");
try
{
    string str = (string)boxed;
    Console.WriteLine(str);
}
catch (InvalidCastException)
{
    Console.WriteLine("InvalidCastException");
}
Output
int 43
string HI
double 7
int[] 2
DateTime
2 1 System.ValueType System.Object
InvalidCastException
  • Verdict: native. object is System.Object, and every type, value types included, inherits from it, as the base types of int and ValueType show. A switch expression with type patterns tests the type of each value. When i becomes an object, it is boxed: the box holds a copy, so it keeps the value 1 after i changes. A cast to the wrong type throws InvalidCastException.
JavaScriptGitHub
const values = [42, "hi", null, undefined, [1], { a: 1 }, () => 1];
console.log(values.map((v) => typeof v).join(" "));
console.log(values.map((v) => v instanceof Object).join(" "));

// Object(v) wraps a primitive in an object, and it makes an empty object for null and undefined.
console.log(values.map((v) => Object(v) instanceof Object).join(" "));

// Most objects inherit from Object.prototype, so they share its methods.
console.log(Object.getPrototypeOf([]) === Array.prototype, Object.getPrototypeOf(Array.prototype) === Object.prototype);
Output
number string object undefined object object function
false false false false true true true
true true true true true true true
true true
  • Verdict: idiom. JavaScript has no static types, so any variable can hold any value. Arrays, plain objects and functions inherit from Object.prototype, but numbers, strings, null and undefined are primitives, so instanceof Object is false for them. Object(v) turns each value into an object.
package main

import "fmt"

func describe(v any) string {
	switch x := v.(type) {
	case int:
		return fmt.Sprint("int ", x+1)
	case string:
		return "string " + x
	case []int:
		return fmt.Sprint("[]int ", len(x))
	case nil:
		return "nil"
	default:
		return fmt.Sprintf("%T", x)
	}
}

func main() {
	values := []any{42, "hi", []int{1, 2}, nil, 3.5}
	for _, v := range values {
		fmt.Println(describe(v))
	}

	// The form with two results reports a failed assertion.
	var v any = 42
	s, ok := v.(string)
	fmt.Printf("%q %v\n", s, ok)

	// The form with one result panics.
	defer func() {
		fmt.Println("recovered:", recover())
	}()
	_ = v.(string)
}
Output
int 43
string hi
[]int 2
nil
float64
"" false
recovered: interface conversion: interface {} is int, not string
  • Verdict: native. any is the empty interface, and every type implements it, so a []any can hold an integer, a string, a slice and nil. A type switch picks the case for the dynamic type. A type assertion with two results returns false when the type is wrong, and the form with one result panics.
RustGitHub
use std::any::Any;

fn describe(v: &dyn Any) -> String {
    if let Some(n) = v.downcast_ref::<i32>() {
        format!("i32 {}", n + 1)
    } else if let Some(s) = v.downcast_ref::<String>() {
        format!("String {}", s.to_uppercase())
    } else if v.is::<&str>() {
        "a &str".to_string()
    } else {
        "unknown".to_string()
    }
}

fn main() {
    let values: Vec<Box<dyn Any>> = vec![
        Box::new(42_i32),
        Box::new(String::from("hi")),
        Box::new("lit"),
        Box::new(3.5_f64),
    ];
    for v in &values {
        println!("{}", describe(v.as_ref()));
    }

    // A downcast to the wrong type gives the box back as an error.
    let b: Box<dyn Any> = Box::new(7_u8);
    match b.downcast::<i32>() {
        Ok(n) => println!("i32 {n}"),
        Err(b) => println!("not an i32, but u8 is {}", b.is::<u8>()),
    }
}
Output
i32 43
String HI
a &str
unknown
not an i32, but u8 is true
  • Verdict: stdlib. Rust has no top type and no root class. The trait object dyn Any stores the type of the value, so downcast_ref and is can test it when the program runs. Code must test each type it knows, and 3.5 matches none of them here. v.as_ref() passes the value in the box, not the box itself.
  • Top versus bottom. The top type contains every value, and the bottom type contains none. A function that takes the top type accepts any argument, and a function that returns the bottom type never returns.
  • Top versus the dynamic type. Any in Python and any in TypeScript accept every value and also fit where any type is expected, so the checker does not check them. A top type only goes up: a value of type object does not fit where a str is expected without a test.
  • Structural top types. "In languages with a structural type system, the empty structure serves as a top type"1. Go's empty interface and the empty object type < > of OCaml are examples1.
  • The top type before generics. Before Java had generics, its collection classes held references of type java.lang.Object1, so each read needed a cast. Generic types, such as List<String>, replaced most of these uses. See type erasure.

Pitfalls

  • A downcast that fails. A cast from the top type to a more specific type is checked only when the program runs. In Java, a wrong cast throws ClassCastException, and in Go, "If the type assertion is false, a run-time panic occurs"6. The examples show both. Test the type first, with instanceof, a type switch or isinstance.
  • any instead of unknown. In TypeScript, any turns off the checks, and in Python, "no type checking is performed when assigning a value of type Any to a more precise type"10. Use unknown or object when the value can have any type but the code still needs checks.
  • Boxing. In C#, "When you convert a value type variable to object, the value is boxed"3. Boxing "allocates an object instance on the heap and copies the value"11, so a change to the copy does not change the original, as the C# example shows. Java has the same cost for int in a List<Object>.
  • Kotlin Any excludes null. A parameter of type Any does not accept null. Use Any? for the top type1.
  • void * loses the type. In C and C++, nothing stops a cast of a void * to the wrong type, and "downcasting from void* cannot be done in a safe way"1. The result is undefined behavior, not an error.

Cost

A variable of the top type must hold any value, so it usually holds a reference to an object, not the value itself. In C# and Java, a value of a primitive or value type is boxed when it becomes an object3, which takes a heap allocation11. Each downcast is a test when the program runs1. In Rust and C++, Box<dyn Any> and std::any store a type identifier with the value, so the downcast can check it97. In Python, every value is already an object, so the type object adds nothing.

History

Smalltalk and JavaScript use Object as the name of their universal base class, and Java has java.lang.Object1. Python made object the base of every class when it unified types and classes in version 2.21. Before Java had generics, its collection classes held references of type java.lang.Object1. TypeScript added unknown as a checked partner of any18, and Go added the predeclared name any for the empty interface6.

References

  1. Any type, Wikipedia, Introduction; Support in programming languages; Other languages
  2. Java SE 25 API, Class Object, Description
  3. Built-in reference types, C# language reference, The object type
  4. Built-in Functions, Python 3.14 documentation, class object
  5. Any, Kotlin Standard Library API reference, Description
  6. The Go Programming Language Specification, Interface types; Type assertions
  7. std::any, C++ reference, cppreference.com, Description
  8. More on Functions, The TypeScript Handbook, Other Types to Know About, unknown
  9. Module std::any, The Rust Standard Library, Any and TypeId
  10. typing, Python 3.14 documentation, The Any type
  11. Boxing and Unboxing, C# programming guide, Boxing

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/2ES327/text.yaml