Programming Search⌘K

Conceptcore

Static and dynamic typing

Also called static typing, dynamic typing, static type checking, dynamic type checking.

Static typing finds type errors before the program runs, from the types of its expressions. Dynamic typing finds them during the run, from the type that each value carries.

Applies to
core-languages

Idea

A type tells which values an expression can have and which operations are valid on them. A type error is an operation on a value of the wrong kind, for example the addition of a string and a number. A language must find type errors at some time, or let the program continue with a wrong result. Static typing finds them before the program runs. A type checker reads the program text and gives a type to each expression.2 Dynamic typing finds them while the program runs. Each value carries its type, and each operation checks the types of its operands.5

Pierce defines a type system as "a tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute".1 Under this definition, a type system is always static. For this reason, Pierce prefers the term "dynamically checked" to "dynamically typed".1 This page uses the usual names, static typing and dynamic typing.

The Python function below has a type error on one branch. Python accepts the function, and the error appears only when that branch runs.

def describe(flag):
    if flag:
        return "count: " + str(3)
    return "count: " + 3


print(describe(True))
try:
    print(describe(False))
except TypeError as error:
    print("TypeError:", error)
Output
count: 3
TypeError: can only concatenate str (not "int") to str

A static checker rejects the same function before any call runs. The next section shows this in Go.

How it works

Static checking. A static type checker runs before the program, usually as a part of the compiler. Java is an example: every variable and every expression has a type that is known at compile time.15 The checker rejects the program when an operation does not fit the types of its operands. The Go version of describe does not compile, although main calls only the good branch.

This code does not compile, on purpose.

package main

import "fmt"

func describe(flag bool) string {
	n := 3
	if flag {
		return "count: " + fmt.Sprint(n)
	}
	return "count: " + n
}

func main() {
	fmt.Println(describe(true))
}

The Go compiler stops with invalid operation: "count: " + n (mismatched types untyped string and int). Go also needs an explicit conversion when an expression mixes two numeric types, for example int and int64.27

Dynamic checking. In a dynamically typed language, a variable has no fixed type. The value carries the type. In Python, every object has an identity, a type and a value, and the type of an object does not change.5 Below, the name x refers to an int and then to a str.

x = 3
print(type(x).__name__)
x = "three"
print(type(x).__name__)
print(isinstance(x, str))
Output
int
str
True

The type is a field of each object. In a release build of CPython, the header of each object holds a reference count and a pointer to the type object.9 An operation such as + reads the type of each operand and looks for an implementation for that pair of types. When it finds none, it raises TypeError, as in Idea.

Mixed checking. Most languages do some checks at each time. A static language keeps run-time checks for operations that the static types cannot decide, such as a cast to a subclass. A dynamic language can add optional annotations that a separate tool checks. The table gives the rule of each tier 1 language.

Language Checked before the run Checked during the run Escape from the static check
Python only by a separate tool; the runtime ignores annotations6 each operation, from the type of each object5 not needed
JavaScript no each operation, from the language type of each value35 not needed
TypeScript by tsc; the types are removed from the output10 as JavaScript any and type assertions11
Java every expression15 casts and array stores1617 casts
C every expression nothing that the language defines casts and implicit conversions19
C++ every expression dynamic_cast21 casts
C# every expression22 casts, and every operation on dynamic23 dynamic23
Go every expression24 type assertions on interface values26 interface types such as any
Rust every expression28 downcast_ref on dyn Any29 dyn Any29
Kotlin every expression as and is30 casts with as
PowerShell no each operation; a typed variable converts each value that it gets31 not needed
SQL (SQLite) no columns of a STRICT table33 not needed
Bash no no; the values are strings34 not needed

Strong and weak typing. This is a separate question. Cardelli and Wegner call a language strongly typed when all its expressions are type-consistent. They state that every statically typed language is strongly typed, but that the converse is not necessarily true.2 In other texts, "weak typing" often means that the language converts an operand to fit an operation instead of reporting an error. This page does not use the two words as labels. It shows what each language does with a mixed operation. JavaScript converts. For +, a string operand makes the operation a concatenation. For -, both operands become numbers.14

console.log("5" + 2);
console.log("5" - 2);
console.log(typeof ("5" - 2));
Output
52
3
number

Python raises TypeError for the same +, as Idea shows. C also converts, but at compile time and with no message. A double assigned to an int loses its fraction.20 A negative value converted to an unsigned type becomes a large positive value.19 The C example and Pitfalls show both.

Soundness. A static type system is sound when no program that passes the checker can have a type error at run time. Milner proved this for his polymorphic type discipline. His Semantic Soundness Theorem states that well-typed programs cannot "go wrong".3 Many languages accept a few unsound rules and keep a run-time check behind them. In Java, an array of String is also an array of Object. The compiler accepts the store of an Integer through the Object[] view, and the store fails at run time.17

This code raises ArrayStoreException, on purpose.

public class Main {
    public static void main(String[] args) {
        Object[] items = new String[2];
        items[0] = "one";
        items[1] = 2;
        System.out.println(items[1]);
    }
}

The TypeScript handbook states that the type system of TypeScript is not sound by design. It allows some operations that the compiler cannot prove safe.12 TypeScript removes all types from the output, so no run-time check stands behind these rules.10 The second pitfall shows the result.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNative
SQLNative
BashNative
PowerShellNative
HTMLDoes not applyMarkup has no expressions that have types.
CSSDoes not applyStyle rules have no expressions that have types.
Regular expressionsDoes not applyA pattern has no typed values.

The example files show, for each language, the type of a value at run time and one checked operation. The table gives the verdict for each tier 1 language.

Language Verdict Form
Python native dynamic; annotations are data that the runtime does not check
JavaScript native dynamic; typeof, with implicit conversion of operands
TypeScript native static checks by tsc over the dynamic rules of JavaScript
Java native static; checked casts and array stores at run time
C native static; implicit arithmetic conversions; no type data at run time
C++ native static; dynamic_cast and std::any for checks at run time
C# native static; dynamic moves the checks to run time
Go native static; interface values with type assertions and type switches
Rust native static; dyn Any with downcast_ref
Kotlin native static; is with smart casts, and as?
PowerShell native dynamic; a type in square brackets fixes the type of a variable
Bash native values are strings; declare -i adds arithmetic on assignment
SQL native in SQLite, the type goes with the value; STRICT tables check columns
Regex n/a a pattern has no typed values
HTML/CSS n/a markup and style rules have no expressions that have types

In SQLite, the datatype of a value is associated with the value itself, not with its container.32 A column type gives only a type affinity, a preferred type. A STRICT table checks the type of each value that goes into a column.33 The SQL example and the pitfalls use SQLite.

In Bash, a variable holds a string, and arithmetic expansion reads the string as a number. The attribute declare -i makes the shell evaluate each assigned value as an arithmetic expression.34 An assignment of text that is not a number gives no error (see the Bash example).

PythonGitHub
for value in [3, 3.0, "3", [3], None]:
    print(type(value).__name__, isinstance(value, (int, float)))


def double(n: int) -> int:
    return n * 2


print(double.__annotations__)
print(double("ab"))
Output
int True
float True
str False
list False
NoneType False
{'n': <class 'int'>, 'return': <class 'int'>}
abab
  • Verdict: native. Python is dynamically typed. A name has no type, and each object carries its type for its whole life.
  • type() gives the class of an object, and isinstance() also accepts subclasses. An operation that has no implementation for its operand types raises TypeError.
  • Annotations are stored in __annotations__ as plain data. The runtime does not check them, so double("ab") returns "abab". A separate tool such as mypy checks them before the run.
  • Python does not convert a str to a number for + or *. It repeats or concatenates sequences, or it raises TypeError.
#include <any>
#include <print>
#include <string>

struct Shape {
    virtual ~Shape() = default;
};
struct Circle : Shape {
    double radius = 1.5;
};
struct Square : Shape {};

int main() {
    Circle circle;
    Square square;
    Shape* shapes[] = {&circle, &square};
    for (Shape* shape : shapes) {
        if (auto* c = dynamic_cast<Circle*>(shape)) {
            std::println("circle, radius {}", c->radius);
        } else {
            std::println("not a circle");
        }
    }

    std::any box = std::string("abc");
    try {
        std::println("{}", std::any_cast<int>(box));
    } catch (const std::bad_any_cast&) {
        std::println("bad_any_cast");
    }
    std::println("{}", std::any_cast<std::string>(box));
}
Output
circle, radius 1.5
not a circle
bad_any_cast
abc
  • Verdict: native. C++ is statically typed. auto infers the type of a variable at compile time.
  • dynamic_cast checks the class of an object of a polymorphic class at run time. A failed cast to a pointer gives nullptr, and a failed cast to a reference throws std::bad_cast.
  • std::any holds a value of any copyable type together with its type. std::any_cast to the wrong type throws std::bad_any_cast.
  • static_cast and reinterpret_cast do no check at run time.
JavaGitHub
import java.util.List;

public class Main {
    static String describe(Object value) {
        if (value instanceof Integer n) {
            return "Integer " + (n + 1);
        }
        if (value instanceof String s) {
            return "String of length " + s.length();
        }
        return value.getClass().getSimpleName();
    }

    public static void main(String[] args) {
        var count = 41;
        Object boxed = count;
        System.out.println(boxed.getClass().getName());
        for (Object value : List.of(count, "abc", 2.5)) {
            System.out.println(describe(value));
        }
    }
}
Output
java.lang.Integer
Integer 42
String of length 3
Double
  • Verdict: native. Java is statically typed. Every variable and expression has a type at compile time, and every object also has a class at run time.
  • var asks the compiler to infer the type of a local variable. Here count is an int, and its type is still fixed.
  • The variable boxed has the static type Object. Its value is an Integer, which getClass() shows.
  • instanceof with a pattern tests the class and binds a variable of the narrower type. A plain cast throws ClassCastException when the class does not fit.
#include <stdio.h>

int main(void) {
    double price = 7.9;
    int whole = price;
    unsigned int big = -1;
    printf("%d\n", whole);
    printf("%u\n", big);
    printf("%zu %zu %zu\n", sizeof(char), sizeof(int), sizeof(double));
    return 0;
}
Output
7
4294967295
1 4 8
  • Verdict: native. C is statically typed. The compiler fixes the type of each object and expression, and nothing records the type at run time.
  • The compiler converts between arithmetic types with no error. A double that goes into an int loses its fraction, and -1 that goes into an unsigned int becomes the maximum value of that type.
  • sizeof gives the size of a type in bytes. The sizes of int and double depend on the platform.

The compiler rejects an assignment between types that have no conversion, such as a struct and an int.

This code does not compile, on purpose.

struct point {
    int x;
    int y;
};

int main(void) {
    struct point p = {1, 2};
    int n = p;
    return n;
}
using Microsoft.CSharp.RuntimeBinder;

var count = 41;
object boxed = count;
Console.WriteLine(boxed.GetType().Name);
if (boxed is int n)
{
    Console.WriteLine(n + 1);
}

dynamic value = "abc";
Console.WriteLine(value.Length);
value = 42;
try
{
    Console.WriteLine(value.Length);
}
catch (RuntimeBinderException error)
{
    Console.WriteLine($"RuntimeBinderException: {error.Message}");
}
Output
Int32
42
3
RuntimeBinderException: 'int' does not contain a definition for 'Length'
  • Verdict: native. C# is statically typed. Each variable has a compile-time type, and each object has a run-time type, which GetType() gives.
  • var infers the compile-time type. is with a pattern tests the run-time type and binds a variable.
  • An expression of type dynamic skips the static check. The runtime binds value.Length at each run, so the error for an int appears only then, as a RuntimeBinderException.
JavaScriptGitHub
const values = [3, "3", true, null, undefined, {}, [], () => 3];
console.log(values.map((v) => typeof v).join(" "));
console.log(Array.isArray([]));

console.log("5" + 2, "5" - 2, "5" * "2");
console.log(0 == "", 0 === "");
console.log(null == undefined, null === undefined);
Output
number string boolean object undefined object object function
true
52 3 10
true false
true false
  • Verdict: native. JavaScript is dynamically typed. Each value has one of the language types, and typeof names it.
  • typeof null gives "object", and typeof [] also gives "object". Use Array.isArray for arrays and === null for null.
  • Operators convert their operands. + concatenates when one operand is a string, and - and * convert both operands to numbers.
  • == converts before it compares, and === does not.
TypeScriptGitHub
type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
  }
}

function isString(value: unknown): value is string {
  return typeof value === "string";
}

console.log(area({ kind: "square", side: 3 }), area({ kind: "circle", radius: 1 }).toFixed(4));
const inputs: unknown[] = ["ab", 3, null];
for (const input of inputs) {
  console.log(isString(input) ? input.toUpperCase() : `not a string: ${input}`);
}
Output
9 3.1416
AB
not a string: 3
not a string: null
  • Verdict: native. TypeScript adds static types to JavaScript. The compiler tsc checks them, and then it removes them from the output.
  • A test such as typeof or a check of the kind field narrows a union type. A function with the return type value is string is a type predicate, which the compiler uses in the same way.
  • The run here strips the types and does no type check. The run-time behaviour is the behaviour of JavaScript.
  • any and as turn off the check. Give outside data the type unknown and narrow it.
package main

import "fmt"

func describe(value any) string {
	switch v := value.(type) {
	case int:
		return fmt.Sprintf("int %d", v+1)
	case string:
		return fmt.Sprintf("string of length %d", len(v))
	default:
		return fmt.Sprintf("other %T", v)
	}
}

func main() {
	var value any = 42
	fmt.Printf("%T\n", value)
	for _, v := range []any{41, "abc", 2.5} {
		fmt.Println(describe(v))
	}
	s, ok := value.(string)
	fmt.Printf("%q %v\n", s, ok)
}
Output
int
int 42
string of length 3
other float64
"" false
  • Verdict: native. Go is statically typed. := infers the type of a variable at compile time.
  • A variable of interface type, such as any, has a static type and a dynamic type. A type switch or a type assertion reads the dynamic type.
  • The form s, ok := value.(string) gives ok == false on a wrong type. The single-value form panics.

This code panics, on purpose.

package main

import "fmt"

func main() {
	var value any = 42
	s := value.(string)
	fmt.Println(s)
}
RustGitHub
use std::any::Any;

fn describe(value: &dyn Any) -> String {
    if let Some(n) = value.downcast_ref::<i32>() {
        format!("i32 {}", n + 1)
    } else if let Some(s) = value.downcast_ref::<&str>() {
        format!("&str of length {}", s.len())
    } else {
        String::from("other")
    }
}

fn main() {
    let count = 41;
    let values: [&dyn Any; 3] = [&count, &"abc", &2.5_f64];
    for value in values {
        println!("{}", describe(value));
    }
    println!("{}", values[0].is::<i64>());
}
Output
i32 42
&str of length 3
other
false
  • Verdict: native. Rust is statically typed. The compiler infers i32 for count and fixes it.
  • dyn Any keeps the type of a value for a check at run time. downcast_ref gives Some for the right type and None for a wrong type, and is gives a bool.
  • Rust does not convert between numeric types by itself. An expression that adds an i32 and an i64 does not compile. Write i64::from(a) or a as i64.

This code does not compile, on purpose.

fn main() {
    let a: i32 = 2;
    let b: i64 = 3;
    println!("{}", a + b);
}
KotlinGitHub
fun describe(value: Any): String = when (value) {
    is Int -> "Int ${value + 1}"
    is String -> "String of length ${value.length}"
    else -> value.javaClass.simpleName
}

fun main() {
    val count = 41
    val values: List<Any> = listOf(count, "abc", 2.5)
    for (value in values) {
        println(describe(value))
    }
    val text: String? = values[0] as? String
    println(text)
    try {
        val s = values[0] as String
        println(s)
    } catch (e: ClassCastException) {
        println("ClassCastException")
    }
}
Output
Int 42
String of length 3
Double
null
ClassCastException
  • Verdict: native. Kotlin is statically typed. val count = 41 infers Int.
  • After a test with is, the compiler treats the value as the tested type in that branch. This is a smart cast.
  • as? gives null when the cast fails. as throws ClassCastException.
CREATE TABLE item (qty INTEGER);
INSERT INTO item VALUES (2), ('3'), ('abc'), (2.5), (NULL);
SELECT qty, typeof(qty) FROM item;
SELECT typeof(1), typeof(1.0), typeof('1'), typeof(x'01');
Output
2|integer
3|integer
abc|text
2.5|real
|null
integer|real|text|blob
  • Verdict: native. This example uses SQLite. In SQLite, the datatype goes with each value, not with the column. typeof gives the storage class of a value.
  • A column type gives a type affinity. In an INTEGER column, SQLite converts the text '3' to an integer and keeps 'abc' as text.
  • A STRICT table rejects a value that does not fit the column type (see Pitfalls on the concept page).
BashGitHub
count=3
echo "$((count + 1))"
echo "$count$count"

declare -i n
n="abc"
echo "$n"
n="2 + 3"
echo "$n"
declare -p n
Output
4
33
0
5
declare -i n="5"
  • Verdict: native. A Bash variable holds a string. Arithmetic expansion $(( )) reads the strings as integers.
  • declare -i gives a variable the integer attribute. Each assignment then evaluates the value as an arithmetic expression.
  • The shell gives no error for text that is not a number. In arithmetic, the word abc is the name of a variable that is not set, so its value is 0.
PowerShellGitHub
$value = 42
$value.GetType().Name
$value = "abc"
$value.GetType().Name

[int]$count = "42"
$count + 1
$count.GetType().Name
try {
    $count = "abc"
} catch {
    $_.Exception.GetType().Name
}

"5" + 2
5 + "2"
Output
Int32
String
43
Int32
ArgumentTransformationMetadataException
52
7
  • Verdict: native. PowerShell variables are loosely typed. A variable can hold an object of any .NET type, and the type goes with the object.
  • A type in square brackets before the variable fixes its type. Each assignment converts the value to that type, and an assignment fails when the value cannot be converted.
  • The left operand decides the operation of +. A string on the left concatenates, and a number on the left converts the right operand to a number.
  • Gradual typing. Siek and Taha add an unknown type, written ?, to a static type system. A part of the program with annotations gets static checks. A part without annotations gets checks at run time. The checker uses a consistency relation between types instead of equality, and ? is consistent with every type.4 TypeScript any turns off the checks for a value,11 and C# dynamic makes the compiler skip the checks for an expression.23
  • Optional checkers. The Python runtime does not enforce annotations.6 PEP 484 states that Python will remain a dynamically typed language, and that the authors have no desire to make type hints mandatory.7 A separate tool, such as mypy, reads the annotations and reports errors. Node.js runs TypeScript files by replacing the types with whitespace, and it does no type check.13
  • Type inference. A static checker can find the types of variables without annotations. Milner gave an algorithm that finds the most general type of each expression of an ML program.3 Rust let, Go :=, C# and Java var, C++ auto and Kotlin val all use inference for local variables (see the examples). Inference does not make a language dynamic. The type is still fixed at compile time.
  • Static type and dynamic type of one variable. A Go variable of interface type has a static type, the interface. It also has a dynamic type, the type of the value that it holds at run time.25 C# uses the terms compile-time type and run-time type in the same way.22 A type switch or a cast reads the dynamic type.
  • Duck typing. A Python program often does not test the type of an object. It calls the method that it needs and lets the object answer.8 A missing method gives an AttributeError at run time.
  • Structural and nominal typing. TypeScript compares types by their members, not by their names.12 In a nominal system, one type is a subtype of another only when a declaration says so.
  • Type parameters. Generics let a static type system describe a container of any element type, so the code needs no casts and no checks at run time.

Pitfalls

Python annotations do not check anything

An annotation in Python is data. The runtime does not enforce it.6 The call below passes a str where the annotation says int, and the function returns a wrong value with no error.

This code runs but gives a wrong answer on purpose.

def area(width: int, height: int) -> int:
    return width * height


print(area(2, 3))
print(area("ab", 2))
Output
6
abab

Run a static checker, such as mypy, on the code before it ships. Where wrong values can come from outside the program, add a check that runs.

def area(width: int, height: int) -> int:
    if not isinstance(width, int) or not isinstance(height, int):
        raise TypeError("area needs two int values")
    return width * height


try:
    area("ab", 2)
except TypeError as error:
    print("TypeError:", error)
Output
TypeError: area needs two int values

A TypeScript type assertion is not a check

A type assertion with as tells the compiler the type of a value. TypeScript removes the assertion from the output, so nothing checks the value at run time.11 Data from JSON.parse has the type that the text gives. Here quantity is a string, and + 1 concatenates.

This code runs but gives a wrong answer on purpose.

const order = JSON.parse('{"quantity": "2"}') as { quantity: number };
console.log(order.quantity + 1);
Output
21

Give outside data the type unknown. Then test it with typeof before the code uses it. The compiler accepts the use only after the test.

function quantityOf(value: unknown): number {
  if (typeof value === "object" && value !== null && "quantity" in value && typeof value.quantity === "number") {
    return value.quantity;
  }
  throw new TypeError("quantity is not a number");
}

try {
  console.log(quantityOf(JSON.parse('{"quantity": "2"}')) + 1);
} catch (error) {
  console.log(String(error));
}
console.log(quantityOf(JSON.parse('{"quantity": 2}')) + 1);
Output
TypeError: quantity is not a number
3

C unsigned arithmetic wraps

The C compiler checks the types, but it converts operands with no message. strlen returns a size_t, which is unsigned. The difference of two size_t values is also unsigned. When the result is negative, the conversion adds one more than the maximum value of the type.19 So the test is true for a shorter string.

This code runs but gives a wrong answer on purpose.

#include <stdio.h>
#include <string.h>

int main(void) {
    const char *a = "ab";
    const char *b = "abc";
    if (strlen(a) - strlen(b) > 0) {
        puts("a is longer");
    } else {
        puts("a is not longer");
    }
    printf("%zu\n", strlen(a) - strlen(b));
    return 0;
}
Output
a is longer
18446744073709551615

Compare the two lengths. Do not subtract them.

#include <stdio.h>
#include <string.h>

int main(void) {
    const char *a = "ab";
    const char *b = "abc";
    if (strlen(a) > strlen(b)) {
        puts("a is longer");
    } else {
        puts("a is not longer");
    }
    return 0;
}
Output
a is not longer

A Java downcast fails at run time

A cast from Object to String passes the compiler. At run time, the cast checks the class of the object and throws ClassCastException when the class does not fit.1618

This code raises ClassCastException, on purpose.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Object> items = new ArrayList<>();
        items.add("one");
        items.add(2);
        for (Object item : items) {
            String text = (String) item;
            System.out.println(text.length());
        }
    }
}

Test the class with instanceof before the code uses the value. The pattern form binds a variable of the narrower type.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Object> items = new ArrayList<>();
        items.add("one");
        items.add(2);
        for (Object item : items) {
            if (item instanceof String text) {
                System.out.println(text.length());
            } else {
                System.out.println("not a string: " + item);
            }
        }
    }
}
Output
3
not a string: 2

A list of a precise type, List<String>, is the better design. Then the compiler rejects items.add(2) (see Generics).

SQLite stores any value in any column

In an ordinary SQLite table, the declared column type is a preference. SQLite converts text that looks like a number. It stores other text as text, in an INTEGER column.32

This code runs but gives a wrong answer on purpose.

CREATE TABLE item (qty INTEGER);
INSERT INTO item VALUES (2), ('3'), ('abc');
SELECT qty, typeof(qty) FROM item;
Output
2|integer
3|integer
abc|text

Declare the table STRICT. Then an insert of a value that does not fit the column type fails with an SQLITE_CONSTRAINT_DATATYPE error.33

This code fails on purpose. The output below is the error.

CREATE TABLE item (qty INTEGER) STRICT;
INSERT INTO item VALUES (2), ('3');
INSERT INTO item VALUES ('abc');

Cost

  • Space for the type. A dynamically typed value must carry its type. Each CPython object has a header with a reference count and a pointer to its type.9 A C int holds only its bits. On the machine of these runs, the two sizes are as follows.
import sys

print(sys.getsizeof(1))
Output
28
#include <stdio.h>

int main(void) {
    printf("%zu\n", sizeof(int));
    return 0;
}
Output
4
  • Time for the check. A dynamic operation reads the types of its operands before it does the work. A static check runs once, at compile time, and adds no work to the run. The run-time checks that a static language keeps have a cost at each use. A Java cast compiles to the checkcast instruction, which tests the class of the object.18 A Java array store also tests the class of the value.17
  • Late binding. An operation on a C# dynamic value is bound at run time by the dynamic language runtime. Overload resolution also happens at run time.23
  • Erased types. TypeScript types do not change the behaviour of the program.10 They cost nothing at run time, and they also check nothing at run time.
  • Gradual code. Siek and Taha designed gradual typing so that the cost of dynamic checks applies only to the parts of a program that use the unknown type.4

History

  • 1978. Robin Milner described a polymorphic type discipline for the language ML. He proved that well-typed programs cannot go wrong, and he gave an algorithm that infers the types.3
  • 1985. Luca Cardelli and Peter Wegner separated static typing from strong typing in their survey of types and polymorphism.2
  • 2002. Benjamin Pierce defined a type system as a static method that proves the absence of some behaviours, in Types and Programming Languages.1
  • 2006. Jeremy Siek and Walid Taha described gradual typing, with the unknown type and the consistency relation.4
  • 2014. PEP 484 defined type hints for Python. It became part of Python 3.5, and it kept the hints optional.7
  • 2021. SQLite 3.37.0 added STRICT tables, which check the type of each value that goes into a column.33

References

  1. Benjamin C. Pierce, Types and Programming Languages, MIT Press, 2002, 1.1 Types in Computer Science
  2. Luca Cardelli and Peter Wegner, On understanding types, data abstraction, and polymorphism, ACM Computing Surveys 17(4), 1985, 1.2 Static and Strong Typing
  3. Robin Milner, A theory of type polymorphism in programming, Journal of Computer and System Sciences 17(3), 1978, pages 348 to 375, the semantic soundness theorem and the well-typing algorithm W
  4. Jeremy G. Siek and Walid Taha, Gradual Typing for Functional Languages, Scheme and Functional Programming Workshop, 2006, pages 81 to 92, Abstract; 2 Introduction to Gradual Typing
  5. The Python Language Reference, Data model, Python 3.14, 3.1 Objects, values and types
  6. The Python Standard Library, typing, Python 3.14, the note at the top of the page
  7. PEP 484: Type Hints, Rationale and Goals, Non-goals; the header fields Created and Python-Version
  8. Python Glossary, Python 3.14, duck-typing
  9. The Python/C API Reference Manual, Common Object Structures, Python 3.14, PyObject
  10. The TypeScript Handbook, The Basics, Erased Types
  11. The TypeScript Handbook, Everyday Types, Type Assertions; any
  12. The TypeScript Handbook, Type Compatibility, A Note on Soundness; the introduction on structural typing
  13. Node.js documentation, Modules, TypeScript, Type stripping
  14. ECMA-262, ECMAScript 2026 Language Specification, 13.15.3 ApplyStringOrNumericBinaryOperator
  15. The Java Language Specification, Java SE 25 Edition, Chapter 4 Types, Values, and Variables, the introduction
  16. The Java Language Specification, Java SE 25 Edition, 5.5 Casting Contexts
  17. The Java Language Specification, Java SE 25 Edition, 10.5 Array Store Exception
  18. The Java Virtual Machine Specification, Java SE 25 Edition, 6.5 Instructions, checkcast
  19. Working Draft, Programming Languages, C (N3220, the C23 draft), 6.3.1.3 Signed and unsigned integers, paragraph 2; 6.3.1.8 Usual arithmetic conversions
  20. Working Draft, Programming Languages, C (N3220, the C23 draft), 6.3.1.4 Real floating and integer, paragraph 1
  21. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [expr.dynamic.cast], paragraphs 7 and 9
  22. C# fundamentals, The C# type system, the introduction; Compile-time type and run-time type
  23. C# advanced topics, Using type dynamic, the introduction; Overload resolution with arguments of type dynamic; Dynamic language runtime
  24. The Go Programming Language Specification, Introduction
  25. The Go Programming Language Specification, Variables (static type and dynamic type)
  26. The Go Programming Language Specification, Type assertions
  27. The Go Programming Language Specification, Numeric types, the last paragraph
  28. The Rust Programming Language, 3.2 Data Types, the introduction
  29. The Rust Standard Library, Module std::any, the module summary; the methods is and downcast_ref of dyn Any
  30. Kotlin documentation, Type checks and casts, Smart casts; Unsafe cast operator; Safe (nullable) cast operator
  31. PowerShell documentation, about_Variables, Types of variables
  32. SQLite documentation, Datatypes In SQLite, 1 Datatypes In SQLite; 3 Type Affinity
  33. SQLite documentation, STRICT Tables, 1 Introduction; 2 STRICT Tables, item 3
  34. Bash Reference Manual, 4.2 Bash Builtin Commands, declare, option -i
  35. ECMA-262, ECMAScript 2026 Language Specification, 6.1 ECMAScript Language Types

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/0R5JMW/text.yaml