Conceptcore
Type system
Also called type system, typing discipline, type checker, type checking, type safety, type soundness, strong typing, weak typing, nominal typing, structural typing, duck typing, untyped language, typed language.
A type system is a set of rules that gives a type to each part of a program and rejects the programs that break the rules. It finds a class of errors before or while the program runs.
- Applies to
- core-languages
Idea
A type system is a set of rules that gives a type to each expression of a program, such as int to n + 1 and bool to n < 10. The rules also say which combinations are wrong, such as adding an integer to a string. A program that breaks a rule is rejected before it runs, or it stops with a type error when it runs. In this way the type system catches a class of mistakes that would otherwise give wrong results without any message.
# A small type system: rules give a type to each expression or reject it.
def type_of(e, env):
match e:
case bool():
return "bool"
case int():
return "int"
case str() if e.startswith('"'):
return "str"
case str():
return env[e] # a variable has the type of its declaration
case ("+", a, b):
ta, tb = type_of(a, env), type_of(b, env)
if ta == tb and ta in ("int", "str"):
return ta
raise TypeError(f"cannot add {ta} and {tb}")
case ("<", a, b):
if type_of(a, env) == type_of(b, env) == "int":
return "bool"
raise TypeError("< needs two ints")
case ("if", c, a, b):
if type_of(c, env) != "bool":
raise TypeError("the condition must be bool")
ta, tb = type_of(a, env), type_of(b, env)
if ta != tb:
raise TypeError(f"the branches have types {ta} and {tb}")
return ta
env = {"n": "int", "name": "str"}
programs = [
("+", "n", 1),
("+", "name", '"!"'),
("if", ("<", "n", 10), '"small"', '"big"'),
("+", "n", '"1"'),
("if", "n", 1, 2),
("if", True, 1, '"one"'),
]
for p in programs:
try:
print("ok ", type_of(p, env))
except TypeError as err:
print("error", err)
ok int
ok str
ok str
error cannot add int and str
error the condition must be bool
error the branches have types int and str
type_of is a small type checker for a language with numbers, strings, +, < and if. Each case is a typing rule: + on two int values gives an int, < gives a bool, and an if needs a bool condition and two branches of the same type. The checker finds the type of each program without running it, so it rejects n + "1" before any value exists. The last program is if True then 1 else "one", which would run without an error, because the condition is always true. The checker rejects it anyway, because its rules look only at types and not at values.
How it works
Purpose. "The fundamental purpose of a type system is to prevent the occurrence of execution errors during the running of a program"1. Wikipedia describes a simple type system as "a set of rules that associates a data type" with "each term (data-valued expression) in a computer program"2. In more developed type systems, "a variety of constructs, such as variables, expressions, functions, and modules, may be assigned types"2.
Typed and untyped languages. Cardelli defines a type through the values that a variable can hold: "An upper bound of such a range is called a type of the variable"1. "Languages where variables can be given (nontrivial) types are called typed languages", and "Languages that do not restrict the range of variables are called untyped languages"1. Assembly language is untyped, because each register holds bits that any instruction can use.
Static and dynamic checking. "Static type checking is the process of verifying the type safety of a program based on analysis of a program's text (source code)"2, and "Dynamic type checking is the process of verifying the type safety of a program at runtime"2. Java uses static checks, and its specification says that "Strong static typing helps detect errors at compile time"3. Python and JavaScript use dynamic checks, so a type error in a line that never runs is never reported. Most statically checked languages also check some things at run time, such as casts, array stores and downcasts. See static and dynamic typing.
Safety. Cardelli separates two kinds of execution errors. A trapped error stops the computation, such as a division by zero. An untrapped error goes on with wrong data, such as "accessing data past the end of an array in absence of run time bounds checks"1. "A program fragment is safe if it does not cause untrapped errors to occur. Languages where all program fragments are safe are called safe languages"1. His table puts ML and Java in the typed and safe group, C in the typed and unsafe group, LISP in the untyped and safe group, and assembler in the untyped and unsafe group1. A safe language can be untyped, because it can check each operation at run time. See undefined behavior.
Strong and weak. The words strong and weak have no single meaning. Cardelli calls a language "weakly checked (or weakly typed, in the literature)" when "some unsafe operations are detected statically and some are not detected"1. In everyday use, a language is also called weakly typed when it converts values of mismatched types, such as JavaScript 1 + "1", and strongly typed when it raises an error, such as Python. It is clearer to say which errors a language detects and when.
Soundness. A type system is sound when the programs that it accepts do not have the errors that it is meant to prevent. Researchers "attempt to prove a type soundness theorem stating that well-typed programs are well behaved"1. A static checker for a general-purpose language must also reject some correct programs. Wikipedia says that "if a type system is both sound (meaning that it rejects all incorrect programs) and decidable (meaning that it is possible to write an algorithm that determines whether a program is well-typed), then it must be incomplete"2. The last program in the example above is such a case.
Nominal and structural types. In a nominal type system, a value has a type only when its declaration says so: a Java class that has an area() method is not a Shape unless it implements Shape. In a structural type system, a value fits a type when it has the right members. "Type compatibility in TypeScript is based on structural subtyping. Structural typing is a way of relating types based solely on their members"4. Go interfaces are structural too. Duck typing is the dynamic form of this idea: Python len(x) works for any object with a __len__ method.
Ways out of the rules. Most type systems have a way for the programmer to override them: a cast in C and Java, dynamic in C#, any in TypeScript, and unsafe in Rust and C#. The Rust book says that "Unsafe Rust exists because, by nature, static analysis is conservative"5, and that with unsafe the programmer tells the compiler, "Trust me, I know what I’m doing"5. Optional type systems go the other way: Python type hints are checked by a separate tool, and "no type checking happens at runtime"6.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript adds a static, structural and gradual type system to JavaScript. any turns the checks off and unknown forces a check, and the compiler erases all types before the program runs. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has a static and nominal type system with nullable types, smart casts after a type check and the safe cast as?. No example file exists because kotlinc is not installed. |
| SQL | Native | SQL gives each column and expression a type and checks it when the statement is prepared or run. The rules for implicit conversions differ between databases. No example file exists. |
| Bash | Does not apply | All Bash values are strings, and Bash has no type checks. declare -i and declare -a only change how a variable is used. |
| PowerShell | Native | PowerShell checks types at run time and converts values with .NET rules, and a type constraint such as [int]$x makes each assignment convert to that type or fail. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no types. A validator checks a document against the content model of each element, which is a different kind of check. |
| CSS | Idiom | Each CSS property has a grammar of valid values, and the browser ignores a declaration whose value does not fit, which acts as a type check. |
| Regular expressions | Does not apply | A regular expression has no types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | dynamic and strong; duck typing; optional hints checked by tools such as mypy |
| JavaScript | native | dynamic and weak; implicit conversions; TypeError for calls on wrong values |
| TypeScript | native | static, structural and gradual over JavaScript; any and unknown; types erased at run time |
| Java | native | static and nominal; checked casts; covariant arrays; erased generics |
| Kotlin | native | static and nominal; nullable types; smart casts; as? |
| C# | native | static and nominal; checked casts; dynamic; unsafe |
| Go | native | static; structural interfaces; no implicit numeric conversions; type assertions |
| Rust | native | static and nominal; traits; no implicit conversions; unsafe for raw operations |
| C | native | static and weak; implicit conversions; void *; unions; casts |
| C++ | native | static; templates and concepts; dynamic_cast; std::variant and std::any |
| Bash | n/a | values are strings, and there are no types to check |
| PowerShell | native | dynamic with optional type constraints such as [int]$x; .NET conversions |
| SQL | native | static types of columns; implicit and explicit CAST; rules differ by database |
| Regex | n/a | no types |
| HTML | n/a | no types; a validator checks the document against the content model |
| CSS | idiom | each property has a value grammar, and an invalid value makes the declaration ignored |
Every general-purpose language has a type system. They differ in when they check types, in which errors they detect, in whether they compare types by name or by structure, and in how a program can step outside the rules.
The example files show these differences. Python reports a type error only when the wrong line runs, uses duck typing and a Protocol, and ignores annotations. JavaScript converts mismatched values, compares with == and ===, and does not check the arguments of a function. Java shows nominal typing, a checked cast, an ArrayStoreException from covariant arrays and a ClassCastException that an unchecked generic cast moves to a later read. C# shows a checked cast, array covariance, dynamic and as. Go satisfies an interface by structure, uses type assertions and keeps types with the same representation apart. Rust checks a trait bound, converts integers with From and TryFrom, downcasts with Any and reads bits in unsafe code. C converts values without a cast and reads a float through a union. C++ uses a concept, dynamic_cast, std::variant and std::any.
from typing import Protocol, get_type_hints, runtime_checkable
# Python checks types when an operation runs, not before.
def describe(x, verbose=False):
if verbose:
return x + 1 # a type error here only matters if this line runs
return f"value {x!r}"
print(describe("a"))
try:
describe("a", verbose=True)
except TypeError as e:
print("TypeError:", e)
# Duck typing: any object with the right method works.
class Ring:
def __len__(self):
return 3
print(len([1, 2]), len("abc"), len(Ring()))
# A Protocol describes a structure; runtime_checkable lets isinstance test it.
@runtime_checkable
class Sized(Protocol):
def __len__(self) -> int: ...
print(isinstance(Ring(), Sized), isinstance(42, Sized))
# Annotations are data for a separate checker, and Python does not enforce them.
def area(w: float, h: float) -> float:
return w * h
print(area("ab", 2), get_type_hints(area))
value 'a'
TypeError: can only concatenate str (not "int") to str
2 3 3
True False
abab {'w': <class 'float'>, 'h': <class 'float'>, 'return': <class 'float'>}
- Verdict: native. Python checks types when an operation runs, so
describe("a")works and the type error in the other branch appears only when that branch runs.lenworks for any object with__len__, which is duck typing. Aruntime_checkableProtocoltests the structure of an object withisinstance. Python does not enforce annotations, soarea("ab", 2)returns"abab", andget_type_hintsreads them as data.
#include <any>
#include <concepts>
#include <print>
#include <string>
#include <variant>
struct Shape {
virtual ~Shape() = default;
};
struct Circle : Shape {};
struct Square : Shape {};
// A concept states what a template needs, and the compiler checks it.
template <std::integral T>
T twice(T x) { return x * 2; }
int main() {
std::println("{} {}", twice(21), twice(10L));
// twice(1.5) does not compile: double does not satisfy std::integral.
// dynamic_cast checks the dynamic type at run time.
Circle c;
Shape* s = &c;
std::println("{} {}", dynamic_cast<Circle*>(s) != nullptr, dynamic_cast<Square*>(s) != nullptr);
// std::variant holds one of several types, and std::get checks which.
std::variant<int, std::string> v = std::string("five");
std::println("{} {}", v.index(), std::holds_alternative<std::string>(v));
try {
std::println("{}", std::get<int>(v));
} catch (const std::bad_variant_access&) {
std::println("bad_variant_access");
}
// std::any holds a value of any type, and any_cast checks the type.
std::any a = 3.5;
try {
std::println("{}", std::any_cast<int>(a));
} catch (const std::bad_any_cast&) {
std::println("bad_any_cast {}", std::any_cast<double>(a));
}
// Implicit conversions from C remain: a double converts to int.
double d = 3.99;
int n = d;
std::println("{}", n);
}
42 20
true false
1 true
bad_variant_access
bad_any_cast 3.5
3
- Verdict: native. A concept such as
std::integralstates what a template needs, and the compiler rejects other types.dynamic_castchecks the dynamic type and givesnullptrwhen it does not match.std::geton astd::variantandstd::any_castcheck the type at run time and throwbad_variant_accessandbad_any_cast. The implicit conversions of C remain, so adoubleconverts toint.
import java.util.ArrayList;
import java.util.List;
public class Main {
interface Shape { double area(); }
record Square(double side) implements Shape { public double area() { return side * side; } }
record Box(double side) { double area() { return side * side; } }
@SuppressWarnings("unchecked")
static <T> T unsafeCast(Object o) { return (T) o; }
public static void main(String[] args) {
// Nominal typing: Box has an area() method but is not a Shape.
Shape s = new Square(2);
Object b = new Box(2);
System.out.println(s.area() + " " + (b instanceof Shape));
// A cast is checked at run time.
Object o = "text";
try {
Integer i = (Integer) o;
System.out.println(i);
} catch (ClassCastException e) {
System.out.println("ClassCastException");
}
// Arrays are covariant, so the check moves to run time.
Object[] objects = new String[1];
try {
objects[0] = 42;
} catch (ArrayStoreException e) {
System.out.println("ArrayStoreException: " + e.getMessage());
}
// Generic types are erased, so an unchecked cast fails later, at the read.
List<String> strings = new ArrayList<>();
List<Integer> ints = unsafeCast(strings);
ints.add(7);
try {
String first = strings.get(0);
System.out.println(first);
} catch (ClassCastException e) {
System.out.println("ClassCastException at the read, size " + strings.size());
}
}
}
4.0 false
ClassCastException
ArrayStoreException: java.lang.Integer
ClassCastException at the read, size 1
- Verdict: native. Java is static and nominal, so
Boxis not aShapealthough it has anarea()method. A cast is checked at run time and throwsClassCastException. Arrays are covariant, so storing anIntegerin aString[]through anObject[]throwsArrayStoreException. Generics are erased, so an unchecked cast lets anIntegerinto aList<String>, and the error appears only when the program reads it.
#include <stdio.h>
#include <stdlib.h>
union Number {
float f;
unsigned u;
};
int main(void) {
/* C converts between arithmetic types without a cast. */
double d = 3.99;
int big = 300;
int i = d;
char c = big;
unsigned u = -1;
printf("%d %d %u\n", i, c, u);
/* void * converts to any object pointer type without a cast. */
void *p = malloc(sizeof(int));
int *ip = p;
*ip = 42;
printf("%d\n", *ip);
free(p);
/* A union lets the program read the bits of one type as another. */
union Number n = {.f = 1.0f};
printf("0x%X\n", n.u);
/* An enum value is an int, and an int converts to an enum. */
enum Color { RED, GREEN, BLUE } color = 7;
printf("%d %d\n", color, GREEN + BLUE);
return 0;
}
3 44 4294967295
42
0x3F800000
7 3
- Verdict: native. C converts between arithmetic types without a cast, so
3.99becomes3,300becomes44in achar, and-1becomes the largestunsigned.void *converts to any object pointer type. A union reads the bits of afloatas anunsigned. An enum variable accepts the value 7, which is not one of its constants.
#:property PublishAot=false
// Static checks: the compiler knows the type of each expression.
object o = "text";
Console.WriteLine(o is string s ? s.Length : -1);
// A cast is checked at run time.
try
{
var i = (int)o;
Console.WriteLine(i);
}
catch (InvalidCastException)
{
Console.WriteLine("InvalidCastException");
}
// Array covariance moves a check to run time.
object[] items = new string[1];
try
{
items[0] = 42;
}
catch (ArrayTypeMismatchException)
{
Console.WriteLine("ArrayTypeMismatchException");
}
// dynamic turns off static checks, and the binder checks at run time.
dynamic d = 5;
Console.WriteLine(d + 1);
d = "five";
Console.WriteLine(d + 1);
try
{
Console.WriteLine(d.NoSuchMethod());
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
{
Console.WriteLine("RuntimeBinderException");
}
// as gives null instead of an exception.
string? t = o as string;
Uri? u = o as Uri;
Console.WriteLine($"{t} {u is null}");
4
InvalidCastException
ArrayTypeMismatchException
6
five1
RuntimeBinderException
text True
- Verdict: native. C# is static and nominal. A pattern
is string stests the type safely, and a cast(int)othrowsInvalidCastException. Array covariance moves a check to run time, where it throwsArrayTypeMismatchException.dynamicturns off static checks, sod + 1is6for a number and"five1"for a string, and a call of a missing method throwsRuntimeBinderException.asgivesnullwhen the type does not match.
// JavaScript checks types at run time and converts values when the types do not match.
console.log(1 + "1", "6" / "2", true + 1, [1] == 1, null == undefined);
// === does not convert, == does.
console.log(0 == "", 0 === "", "1" == 1, "1" === 1);
// A wrong operation either converts, gives NaN or throws a TypeError.
console.log("abc" * 2, undefined + 1);
try {
const n = 5;
n.toUpperCase();
} catch (e) {
console.log(e.constructor.name, e.message);
}
// A function does not check the number or the types of its arguments.
function add(a, b) {
return a + b;
}
console.log(add(1, 2), add(1), add("1", 2), add(1, 2, 3));
// Duck typing: an object with a next() method works as an iterator.
const counter = { i: 0, next() { return this.i < 3 ? { value: this.i++, done: false } : { done: true }; } };
console.log([...{ [Symbol.iterator]: () => counter }]);
11 3 2 true true
true false true false
NaN NaN
TypeError n.toUpperCase is not a function
3 NaN 12 3
[ 0, 1, 2 ]
- Verdict: native. JavaScript checks types at run time and converts mismatched values, so
1 + "1"is"11"and"6" / "2"is3.==converts before it compares, and===does not. A wrong arithmetic operation givesNaN, and a call of a value that is not a function throws aTypeError. A function accepts any number of arguments of any type.
package main
import (
"fmt"
"strings"
)
// Shape is satisfied by any type with an Area method: no declaration is needed.
type Shape interface{ Area() float64 }
type Square struct{ Side float64 }
func (s Square) Area() float64 { return s.Side * s.Side }
type Seconds int64
type Meters int64
func main() {
var s Shape = Square{2}
fmt.Println(s.Area())
// A type assertion checks the dynamic type at run time.
var x any = "text"
if n, ok := x.(int); !ok {
fmt.Println("not an int", n)
}
str, ok := x.(fmt.Stringer)
fmt.Println(str, ok)
// Go has no implicit numeric conversions, even between types with the same representation.
var t Seconds = 90
var d Meters = 400
fmt.Println(int64(t)+int64(d), Meters(t) == d)
// Untyped constants have arbitrary precision until they get a type.
const big = 1 << 100
fmt.Println(big>>98, 1.0/3*3 == 1)
// A failed assertion without ok panics.
defer func() { fmt.Println("recovered:", strings.SplitN(fmt.Sprint(recover()), ":", 2)[0]) }()
_ = x.(int)
}
4
not an int 0
<nil> false
490 false
4 true
recovered: interface conversion
- Verdict: native.
SquaresatisfiesShapebecause it has anAreamethod, with no declaration. A type assertion withoktests the dynamic type, and one withoutokpanics when it fails.SecondsandMetershave the same representation but do not mix without a conversion. Untyped constants keep full precision, so1 << 100is valid as a constant.
use std::any::Any;
use std::fmt::Display;
// A trait bound is checked when the program compiles.
fn show_all<T: Display>(items: &[T]) -> String {
items.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(",")
}
fn main() {
println!("{} {}", show_all(&[1, 2, 3]), show_all(&["a", "b"]));
// No implicit conversions: u8 to u32 needs From, and u32 to u8 needs a fallible try_from.
let small: u8 = 200;
let wide: u32 = u32::from(small) + 100;
println!("{} {:?} {:?}", wide, u8::try_from(wide), u8::try_from(100u32));
// Any gives a checked downcast at run time.
let values: Vec<Box<dyn Any>> = vec![Box::new(5i32), Box::new("five")];
for v in &values {
match v.downcast_ref::<i32>() {
Some(n) => println!("i32 {n}"),
None => println!("not an i32"),
}
}
// unsafe code may break the rules, so the programmer must check it.
let f = 1.0f32;
let bits: u32 = unsafe { *(&f as *const f32 as *const u32) };
println!("{bits:#x} {:#x}", f.to_bits());
}
1,2,3 a,b
300 Err(TryFromIntError(PosOverflow)) Ok(100)
i32 5
not an i32
0x3f800000 0x3f800000
- Verdict: native. A trait bound such as
T: Displayis checked at compile time. Rust has no implicit numeric conversions:u32::fromwidens au8, andu8::try_fromreturns an error when the value does not fit.Anygives a checked downcast at run time. In anunsafeblock, a pointer cast reads the bits of anf32as au32, and the programmer must make sure that this is valid.
Variations and related ideas
- Type inference. The compiler finds most types without annotations, as in ML, Haskell, Rust and Go
:=. See Hindley-Milner type inference. - Gradual typing. TypeScript, Python with type hints and C# with
dynamicmix static and dynamic checks in one program. See gradual types. - Subtyping. A value of a subtype can be used where a value of its supertype is expected. See subtyping.
- Polymorphism. Generics, overloading and subtyping let one piece of code work with many types. See parametric polymorphism.
- Richer types. Dependent types put values in types, linear and affine types control how often a value is used, and effect systems track side effects. See dependent types.
Pitfalls
- Trusting a cast. A cast in C tells the compiler to stop checking, and a wrong cast is undefined behavior. In Java and C#, a wrong cast throws an exception only when the program runs.
- Unsound holes. Covariant arrays in Java and C#, erased generics in Java, and
anyin TypeScript let a wrong value pass the static check, and the error appears later, far from its cause. - Implicit conversions. C converts
3.99to3and-1to a large unsigned value without a cast, and JavaScript converts strings and numbers. Many compilers and linters can warn about these conversions. - Annotations that do not run. Python type hints and TypeScript types do not exist at run time, so data from a file or a network must be checked by the program.
- Arguing about strong and weak. These words mean different things to different people. Say instead what the language checks and when it checks it.
Cost
Static checks cost compile time but nothing at run time, and they let the compiler drop run-time checks and choose fast machine instructions. Wikipedia notes that a compiler that proves a program well-typed "does not need to emit dynamic safety checks, allowing the resulting compiled binary to run faster and to be smaller"2. Dynamic checks cost a test of the type tag at each operation, which JIT compilers reduce by guessing types and checking the guess. Rich static type systems can make compile times long, and C++ templates and TypeScript types can be slow to check.
History
Early languages such as FORTRAN and ALGOL 60 had a few built-in types and simple rules for them. Pascal, Simula 67 and C added types that a program defines. In 1978, Robin Milner published a paper on type inference for ML. Cardelli writes that it "brought the study of type systems and type inference to a new level", and that "It includes an algorithm for polymorphic type inference, and the first proof of type soundness for a (simplified) programming language"1. Later work added subtyping, generics and type classes, and languages such as Java, C#, Rust, TypeScript and Swift brought these ideas into wide use.
References
- Luca Cardelli, Type Systems, CRC Handbook of Computer Science and Engineering, 2nd Edition, Chapter 97, 2004, 1 Introduction; How type systems are formalized; Further Information
- Type system, Wikipedia, Introduction; Static type checking; Dynamic type checking and runtime type information
- The Java Language Specification, Java SE 25 Edition, Chapter 4, Chapter 4 introduction
- Type Compatibility, TypeScript Handbook, Introduction
- Unsafe Rust, The Rust Programming Language, Introduction; Unsafe Superpowers
- PEP 484, Type Hints, Rationale and Goals; Non-goals
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 EW24J7 Edit this page History Report an error Markdown