Conceptcore
Gradual typing
Also called gradual typing, optional typing, type hints, the dynamic type, any type, unknown type, consistency, casts, blame, migratory typing, sound gradual typing.
Gradual typing lets one program mix code with static types and code without them. An unknown type matches every type, and checks at the boundary catch values of the wrong type when the program runs.
- Applies to
- core-languages
Idea
Gradual typing lets one program mix code that has static types with code that does not. Code without annotations gets an unknown type, often written ?, Any or dynamic, and the checker lets a value of the unknown type go wherever a typed value can go. Where a value moves from unknown to known types, a sound gradual system inserts a check that runs when the program runs, so a value of the wrong type fails at the boundary, with the blame on the untyped side. A team can then add types to a large program one module at a time. TypeScript, Python's type hints, PHP's types, C#'s dynamic and Racket's typed modules all follow this idea, with different degrees of checking.
DYN = "?" # the unknown type of gradual typing
def consistent(a, b): # like equality, but "?" matches every type
if DYN in (a, b):
return True
if isinstance(a, tuple) and isinstance(b, tuple): # function types
return len(a) == len(b) and all(map(consistent, a, b))
return a == b
def check_call(fn_type, arg_type): # the static check at a call
param, result = fn_type
if not consistent(param, arg_type):
return f"static error: {arg_type} is not consistent with {param}"
if param != arg_type: # a cast is needed where "?" meets a known type
return f"ok, with a run-time cast from {arg_type} to {param}"
return "ok, no cast"
def cast(value, typ, blame): # the run-time check that the cast inserts
if typ != DYN and type(value).__name__ != typ:
raise TypeError(f"{blame}: expected {typ}, got {type(value).__name__}")
return value
print(consistent("int", DYN), consistent(("int", "str"), (DYN, "str")),
consistent("int", "str"))
double = ("int", "int")
for arg in ["int", DYN, "str"]:
print(f"double(<{arg}>):", check_call(double, arg))
for value in [21, "21"]: # a value of type "?" reaches the typed function
try:
print("double:", 2 * cast(value, "int", "the caller of double"))
except TypeError as err:
print("blame ->", err)
True True False
double(<int>): ok, no cast
double(<?>): ok, with a run-time cast from ? to int
double(<str>): static error: str is not consistent with int
double: 42
blame -> the caller of double: expected int, got str
The checker uses consistency in place of equality: ? is consistent with every type, and two function types are consistent when their parts are. A call with an int needs no check, a call with a str is a static error, and a call with a ? passes the static check but gets a cast. The cast lets 21 through and stops "21" at the boundary, with a message that blames the untyped code that supplied it.
How it works
The unknown type. A gradual type system adds one type, the unknown or dynamic type, to a static type system. Python's documentation describes its rules: "A static type checker will treat every type as assignable to Any and Any as assignable to every type."1 Code that has no annotations is treated as if every name had this type, so the checker accepts it as it is. Jeremy Siek, who invented the approach "with Walid Taha", describes it as "mixing static and dynamic type checking within the same language".2
Consistency, not subtyping. The unknown type cannot be a normal supertype of every type, because then every type would be a subtype of every other through it, and the checker would accept anything. Gradual typing uses a separate relation, consistency, which is not transitive: int is consistent with ? and ? with str, but int is not consistent with str. The checker still rejects errors between known types, as the example shows.
Casts and blame. In a sound gradual system the compiler inserts a cast wherever a value of the unknown type flows into a known type, and the reverse for functions and objects that cross the boundary. A failed cast stops the program at the boundary, not deep inside the typed code, and blame tracking names the side that broke the agreement. The result is a guarantee: typed code never sees a value of the wrong type, and any error is the fault of untyped code. Typed Racket gives this guarantee with contracts at module boundaries.
Optional typing. Most gradual systems in wide use leave out the casts. TypeScript removes all types when it compiles to JavaScript, and PEP 484 states for Python that "no type checking happens at runtime".3 These systems find errors in typed code before it runs, but a wrong value from untyped code, a JSON file or a cast travels on and fails later, or not at all. The trade gives no run-time cost and easy adoption for a weaker guarantee, which the community calls optional or unsound gradual typing. PEP 484 also states the aim: "Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention."3
Migration. The practical use of gradual typing is migration. A team adds annotations to the modules where errors cost the most, turns on stricter checks file by file, and ends with most code typed. TypeScript's noImplicitAny option marks each place where the type silently became any, because "any isn’t type-checked".4 Mypy and Pyright have similar strict modes. By default mypy does not check the body of a function that has no annotations.
Static languages with a dynamic type. Statically typed languages approach the same mix from the other side. C# has dynamic, and "an object of type dynamic bypasses static type checking".5 Java, Go, Rust and C++ have a type that holds any value, Object, any, dyn Any and std::any, together with casts or downcasts that check the type when they run. The C++ standard library describes std::any as "a type-safe container for single values of any copy constructible type".6 These are checked dynamic typing inside a static language; they do not let a program leave out types.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Idiom | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Absent | |
| TypeScript | Native | TypeScript is a gradual layer over JavaScript, with any and unknown types and the noImplicitAny and strict options; the types are removed before the code runs. |
| Go | Idiom | |
| Rust | Standard library | |
| Kotlin | Idiom | Kotlin is statically typed with Any, safe casts with as? and smart casts after is checks, and a dynamic type only when it compiles to JavaScript; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | Columns have declared types, and the database checks or converts values when it stores them. |
| Bash | Does not apply | Every value is a string, and declare -i only changes how assignment works. |
| PowerShell | Native | Variables are untyped unless a type constrains them, as in [int]$n, and each later assignment to a constrained variable is converted or rejected when it runs; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no types. |
| CSS | Does not apply | Properties have value grammars, not types that a program declares. |
| Regular expressions | Does not apply | Patterns have no types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | annotations, typing.Any, mypy and Pyright; no checks at run time |
| JavaScript | absent | no annotations; TypeScript and Flow add them |
| TypeScript | native | any and unknown; types removed before the code runs |
| Java | idiom | Object, checked casts, instanceof, type patterns |
| Kotlin | idiom | Any, is and as?; dynamic on the JavaScript target |
| C# | native | the dynamic type and the run-time binder |
| Go | idiom | any, type assertions and type switches |
| Rust | stdlib | std::any::Any and downcasts |
| C | idiom | tagged unions; void * with no check |
| C++ | stdlib | std::any, std::any_cast, std::variant |
| Bash | n/a | every value is a string |
| PowerShell | native | untyped variables, or types that constrain them |
| SQL | n/a | declared column types |
| Regex | n/a | no types |
| HTML | n/a | no types |
| CSS | n/a | no types |
Python, TypeScript, C# and PowerShell let one program choose, name by name, between static and dynamic checking, so they are native. Python and TypeScript start from a dynamic language and add optional static types that do not run; C# starts from a static language and adds a dynamic type whose operations the run-time binder checks. PowerShell checks types when it runs, and only for variables that declare one.
Java, Go, Rust, C and C++ are static languages with one escape: a type that holds any value, and a checked way to get the real type back. The example files show each form: the checked casts and type patterns of Java, Go's type switch over decoded JSON, Rust's downcasts, C's tagged union and C++'s std::any. The JavaScript file writes contracts with blame by hand, and the Python file shows that annotations are not checked unless code checks them at the boundary.
import inspect
from typing import Any, get_type_hints
def area(width: int, height: int) -> int:
return width * height
print(get_type_hints(area))
print(area("ab", 3)) # Python does not check annotations when it runs
def checked(fn): # check the annotations at the boundary, as a cast would
hints, sig = get_type_hints(fn), inspect.signature(fn)
def wrapper(*args):
for name, value in sig.bind(*args).arguments.items():
want = hints.get(name, Any)
if want is not Any and not isinstance(value, want):
raise TypeError(f"{fn.__name__}: {name} must be {want.__name__}, "
f"got {type(value).__name__}")
return fn(*args)
return wrapper
safe_area = checked(area)
print(safe_area(4, 5))
try:
safe_area("ab", 3)
except TypeError as err:
print(err)
{'width': <class 'int'>, 'height': <class 'int'>, 'return': <class 'int'>}
ababab
20
area: width must be int, got str
- Verdict: native. Python has annotations in its syntax,
typing.Anyas the unknown type, and separate checkers such as mypy and Pyright that check annotated code and trust unannotated code. The interpreter does not check annotations, soarea("ab", 3)runs and repeats the string. The decorator reads the annotations withget_type_hintsand checks the arguments at the call, which is the cast that a sound gradual system would insert. Libraries such as typeguard and beartype do this for real code.
#include <any>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::any> values{21, std::string("hello"), 1.5};
for (const auto& v : values) {
if (const int* n = std::any_cast<int>(&v)) {
std::cout << "int, doubled " << *n * 2 << '\n';
} else if (const auto* s = std::any_cast<std::string>(&v)) {
std::cout << "string of length " << s->size() << '\n';
} else {
std::cout << "other type\n";
}
}
try {
std::cout << std::any_cast<int>(values[1]) << '\n';
} catch (const std::bad_any_cast&) {
std::cout << "bad_any_cast: the value is not an int\n";
}
}
int, doubled 42
string of length 5
other type
bad_any_cast: the value is not an int
- Verdict: stdlib.
std::any, from C++17, holds one value of any copyable type and remembers its type.std::any_caston a pointer returns null when the type does not match, and on a value it throwsstd::bad_any_cast.std::variantis the alternative when the set of types is known.
import java.util.List;
public class Main {
public static void main(String[] args) {
Object value = "42"; // the static type forgets the class
if (value instanceof String s) { // a checked test, then a typed name
System.out.println("a String of length " + s.length());
}
try {
Integer n = (Integer) value; // a cast is checked when it runs
System.out.println(n + 1);
} catch (ClassCastException e) {
System.out.println("ClassCastException at the cast");
}
List<Object> mixed = List.of(1, "two", 3.0);
for (Object o : mixed) {
String kind = switch (o) {
case Integer i -> "Integer " + (i + 1);
case String t -> "String " + t.toUpperCase();
default -> "other " + o.getClass().getSimpleName();
};
System.out.println(kind);
}
}
}
a String of length 2
ClassCastException at the cast
Integer 2
String TWO
other Double
This code runs but gives a wrong answer on purpose.
import java.util.ArrayList;
import java.util.List;
public class Main {
@SuppressWarnings({"rawtypes", "unchecked"})
static void addLegacy(List list) { // a raw type: no type arguments
list.add("not a number"); // the compiler cannot check this
}
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(1, 2));
addLegacy(numbers);
System.out.println("size " + numbers.size());
try {
int sum = 0;
for (Integer n : numbers) sum += n; // the hidden cast fails here
System.out.println(sum);
} catch (ClassCastException e) {
System.out.println("ClassCastException far from the cause");
}
}
}
size 3
ClassCastException far from the cause
- Verdict: idiom. Java is statically typed, with
Objectas the type that every class fits and casts,instanceofand pattern matching that check the class at run time. The run block shows the checked forms: a failed cast throws at the cast, and aswitchwith type patterns names each case. - The wrong block passes a
List<Integer>to a method that takes a rawList, the type of code written before generics. The compiler cannot check the raw call, so a string enters a list of integers, and the error appears later, at the hidden cast in the loop. The JLS calls this heap pollution. Fix the legacy method to takeList<Integer>, and treat unchecked warnings as errors.
#include <stdio.h>
/* A dynamic value: a tag that says which member of the union is valid. */
enum kind { INT, TEXT };
struct value {
enum kind kind;
union {
int i;
const char *s;
} as;
};
static int as_int(struct value v, int *out) { /* a checked cast */
if (v.kind != INT) return 0;
*out = v.as.i;
return 1;
}
int main(void) {
struct value vals[] = {{INT, {.i = 21}}, {TEXT, {.s = "21"}}};
for (int k = 0; k < 2; k++) {
int n;
if (as_int(vals[k], &n))
printf("double: %d\n", 2 * n);
else
printf("cast failed: the value holds text \"%s\"\n", vals[k].as.s);
}
return 0;
}
double: 42
cast failed: the value holds text "21"
- Verdict: idiom. C has
void *, which holds a pointer to any type with no check at all, so a wrong cast is undefined behavior, not an error. The checked form is a tagged union: a field records which member is valid, and a function tests the tag before it reads the member, as interpreters for dynamic languages written in C do.
using System;
using Microsoft.CSharp.RuntimeBinder;
static dynamic Twice(dynamic x) => x + x; // resolved when it runs
Console.WriteLine(Twice(21));
Console.WriteLine(Twice("ab"));
Console.WriteLine(Twice(1.5));
dynamic d = "text";
int typed = 5;
Console.WriteLine(d.Length + typed); // the binder finds Length on string
try
{
Console.WriteLine(d.Count); // string has no Count property
}
catch (RuntimeBinderException e)
{
Console.WriteLine("RuntimeBinderException: " + e.Message);
}
try
{
int n = d; // a conversion from dynamic is checked when it runs
Console.WriteLine(n);
}
catch (RuntimeBinderException)
{
Console.WriteLine("cannot convert the string to int");
}
42
abab
3
9
RuntimeBinderException: 'string' does not contain a definition for 'Count'
cannot convert the string to int
- Verdict: native. C# has the static type
dynamic, added in C# 4.0: the compiler skips checks for adynamicvalue and records each operation, and the run-time binder resolves the operation with the actual type.Twiceworks onint,stringanddouble, a missing member throwsRuntimeBinderException, and assigning adynamicvalue to anintvariable checks the conversion when it runs. Code that does not usedynamickeeps all of its static checks.
// A contract wraps a function and checks its arguments and result at the
// boundary between checked and unchecked code, and names the party to blame.
function contract(fn, params, result, name) {
return (...args) => {
params.forEach((type, i) => {
if (typeof args[i] !== type) {
throw new TypeError(`${name}: caller broke the contract: argument ${i} is ${typeof args[i]}, not ${type}`);
}
});
const out = fn(...args);
if (typeof out !== result) {
throw new TypeError(`${name}: function broke the contract: result is ${typeof out}, not ${result}`);
}
return out;
};
}
const add = contract((a, b) => a + b, ["number", "number"], "number", "add");
const label = contract((n) => (n > 0 ? "positive" : 0), ["number"], "string", "label");
console.log("unchecked:", ((a, b) => a + b)("1", 2)); // plain JavaScript joins the strings
for (const call of [() => add(1, 2), () => add("1", 2), () => label(5), () => label(-5)]) {
try {
console.log(call());
} catch (err) {
console.log(err.message);
}
}
unchecked: 12
3
add: caller broke the contract: argument 0 is string, not number
positive
label: function broke the contract: result is number, not string
- Verdict: absent. JavaScript has no type annotations; TypeScript and Flow add them as separate languages that compile to JavaScript and remove the types. The example writes a contract in the style of Racket: a wrapper checks the arguments and the result of a function at the boundary and reports which side broke the agreement. Bad arguments blame the caller, and a bad result blames the function, which is the blame that gradual type systems assign to casts.
package main
import (
"encoding/json"
"fmt"
)
func main() {
var doc any // the empty interface: a value of any type
if err := json.Unmarshal([]byte(`{"name": "ada", "year": 1815, "tags": ["math"]}`), &doc); err != nil {
panic(err)
}
m := doc.(map[string]any) // a type assertion, checked when it runs
for _, key := range []string{"name", "year", "tags"} {
switch v := m[key].(type) {
case string:
fmt.Println(key, "is a string:", v)
case float64: // JSON numbers decode as float64
fmt.Println(key, "is a float64:", v)
case []any:
fmt.Println(key, "is a list of", len(v))
}
}
if _, ok := m["year"].(int); !ok {
fmt.Println("year is not an int")
}
}
name is a string: ada
year is a float64: 1815
tags is a list of 1
year is not an int
- Verdict: idiom. Go is statically typed, with
any, the empty interface, as the type that holds a value of any type. A type assertion or a type switch gets the concrete type back and is checked when it runs: the formv, ok := x.(T)reports failure, and the form withoutokpanics. JSON decoded intoanyshows the cost of losing the static type: numbers come back asfloat64, so the assertion tointfails.
use std::any::Any;
fn describe(value: &dyn Any) -> String {
if let Some(n) = value.downcast_ref::<i32>() {
format!("an i32, doubled {}", n * 2)
} else if let Some(s) = value.downcast_ref::<String>() {
format!("a String of {} bytes", s.len())
} else {
"something else".to_string()
}
}
fn main() {
let values: Vec<Box<dyn Any>> = vec![Box::new(21_i32), Box::new(String::from("hello")), Box::new(1.5_f64)];
for v in &values {
println!("{}", describe(v.as_ref()));
}
let boxed: Box<dyn Any> = Box::new(7_u8);
match boxed.downcast::<i32>() {
Ok(n) => println!("got {n}"),
Err(_) => println!("downcast to i32 failed: the value is not an i32"),
}
}
an i32, doubled 42
a String of 5 bytes
something else
downcast to i32 failed: the value is not an i32
- Verdict: stdlib. Rust is statically typed, and
std::any::Anygives a checked form of dynamic typing for values whose type is not known where they are used.downcast_refreturnsNoneandBox::downcastreturnsErrwhen the type does not match, so the program must handle the failure. Au8does not downcast toi32: there are no conversions, only an exact match of the type.
Variations and related ideas
- Sound gradual typing. Typed Racket, Reticulated Python and Grace insert casts at every boundary and keep the guarantee that typed code sees only values of its types.
- Transient checks. A cheaper form, used by Reticulated Python, checks only the outer shape of a value, such as "is a list", where it enters typed code, and checks the parts when typed code reads them.
- Optional typing. TypeScript, Flow, mypy, Pyright, Sorbet for Ruby and Hack's original mode check types before the program runs and remove them. Dart 1 was optionally typed; Dart 2 made its types sound. See static and dynamic typing.
- Concrete types. Some research designs, such as Thorn, StrongScript and Nom, check types at run time only for classes, which makes the checks fast.
- The unknown type in TypeScript.
unknownholds any value but allows no operation until code checks its type, a safer form ofany. - Type inference. Inference fills in types without annotations, and gradual languages use it to reduce the code that falls back to the unknown type. See Hindley-Milner.
- Contracts. Racket's contracts and design by contract check values at boundaries with any predicate, not only types. See assertions.
Pitfalls
- Any spreads. An operation on a value of type
AnygivesAny, so one unannotated function can turn a whole chain of expressions into unchecked code. Turn onnoImplicitAnyin TypeScript and thedisallow_any_genericsoption and strict mode in mypy, and preferunknownorobjectwhen the type is truly not known. - Types that lie. In an optional system, an annotation is a claim, not a check. JSON, user input and calls from untyped code can give values that do not match, and the error appears far from the cause. Validate data where it enters the program.
- Raw and unchecked types. Java's raw types and unchecked casts let a value of the wrong type into a generic collection; the JLS calls the result heap pollution.7 The wrong block in the Java file shows the late failure. Treat unchecked warnings as errors.
- Casts with no check. TypeScript's
as, C's casts andstatic_castin C++ tell the compiler to trust the programmer, and nothing checks them when the program runs. - The cost of sound checks. Casts on functions and objects wrap them in proxies, and a value that crosses many boundaries can collect many wrappers. Programs in sound gradual systems have run many times slower when typed and untyped modules call each other in a loop.
Cost
Optional systems such as TypeScript and Python's type hints cost nothing at run time, because the types are removed or ignored. A dynamic type in a static language, such as C#'s dynamic, costs a call to the run-time binder for each operation, which caches the result for each call site after the first call. std::any puts values larger than a small buffer on the heap, Box<dyn Any> always does, and each cast compares a type identifier. Sound gradual systems pay for a check at each boundary and for a wrapper around each function or object that crosses it; the cost depends on how often values cross, and it was the main research problem of the field after 2015.
History
Lisp compilers accepted optional type declarations from the 1970s, and Common Lisp, from 1984, and Dylan used them to generate faster code. Erik Meijer and Peter Drayton argued in 2004 for static typing where possible and dynamic typing where needed. Jeremy Siek and Walid Taha named gradual typing and defined consistency in a 2006 paper,2 and in the same year Sam Tobin-Hochstadt and Matthias Felleisen described the migration from untyped to typed Scheme code, the work that became Typed Racket. Philip Wadler and Robert Bruce Findler added blame to gradual types in 2009.
Industry adopted the idea from 2010. C# 4.0 added dynamic in 2010.5 Microsoft released TypeScript in 2012, which Siek describes as "a gradually-typed dialect of JavaScript".2 Facebook released Hack, a typed dialect of PHP, and Flow for JavaScript in 2014, and PEP 484 added type hints to Python 3.5 in 2015.3 Research then turned to the cost of sound checks, after a 2016 study found large slowdowns in Typed Racket programs that mixed typed and untyped modules.
References
- typing, Support for type hints, Python documentation, The Any type
- Jeremy G. Siek, home page, Indiana University, Introduction and Technology Transfer
- PEP 484, Type Hints, Rationale and goals
- Everyday Types, The TypeScript Handbook, any and noImplicitAny
- Using type dynamic, C# documentation, Introduction
- std::any, cppreference.com, Description
- Chapter 4, Types, Values, and Variables, The Java Language Specification, Java SE 25 Edition, 4.12.2 Variables of Reference Type
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 0B7HTJ Edit this page History Report an error Markdown