Gradual typing is an approach to type systems that allows statically typed and dynamically typed code to coexist within a single programming language. Programs may specify precise types for some values while leaving other types unknown, and programmers can increase or decrease the amount of type information incrementally. In its formal sense, gradual typing concerns not only optional annotations but also the rules governing incomplete type information and the behavior of interactions between typed and untyped code. Implementations differ substantially in whether they enforce types at runtime.
Motivation and basic model
Static typing checks properties of a program before execution, typically rejecting operations inconsistent with the types assigned to their operands. Dynamic typing checks the applicability of operations during execution. Gradual typing combines these approaches: statically known information supports early error detection, while unknown information permits operations whose validity cannot be established until execution.
A central mechanism is an unknown type, conventionally written , though practical languages use names such as Any or dynamic, with language-specific meanings.
For example, consider this language-neutral pseudocode:
function increment(x: Integer) -> Integer:
return x + 1
value: ? = obtain_external_value()
result = increment(value)
The checker knows that increment requires an integer, but not whether value is one. A gradually typed system may accept the call. In a runtime-enforced implementation, execution checks that the value satisfies the required type and reports a type error if it does not.
By contrast, passing a value statically known to be a string can be rejected before execution. Unknown information permits a check to be deferred; it does not establish that every value has the required type.
This arrangement supports incremental migration of existing programs. Libraries, functions, or modules can acquire types without requiring the entire codebase to be converted at once. It also allows a typed core to interact with dynamic extensions or external inputs.
Consistency, subtyping, and precision
Gradual typing distinguishes several relationships that conventional explanations sometimes conflate.
Type consistency
In a simple gradual type system, consistency expresses whether two types could agree once their unknown parts are resolved. If denotes consistency, then:
However:
Consistency is therefore generally not transitive. If it were transitive, the unknown type would make otherwise incompatible types consistent with one another.
For compound types, consistency can be defined structurally. For example, a function type can be consistent with , because the unknown parameter type could be resolved as String.
Difference from subtyping
Subtyping describes when a value of one type may safely be used where another type is expected. A top type, such as an ordinary Object type in some languages, can receive values of more specific types, but using such a value as a specific type generally requires further evidence.
The gradual unknown type has a different role: it permits interactions in both directions, potentially supported by runtime checks. It is therefore not simply an ordinary top type. Practical languages may blur this distinction by giving their universal or dynamic types additional rules.
Type precision
A precision relation compares how much information types contain. An integer type is more precise than an unknown type; a list of integers is more precise than a list whose element type is unknown.
Precision is not the same as subtyping. Replacing an unknown type with Integer adds information, but it does not necessarily describe the substitutability relation captured by a language’s subtype hierarchy.
These distinctions are important when specifying how adding annotations should affect a program.
Runtime enforcement
A gradually typed compiler or interpreter may insert checks or casts where statically known and unknown information interact. These checks are often absent from the original source code.
For simple values, enforcement may be straightforward: a value entering an integer-typed context must be an integer. For functions, objects, and mutable containers, enforcement is more complicated.
Higher-order values and wrappers
Suppose dynamically typed code supplies a function to a typed context expecting:
Checking that the supplied value is callable does not establish that it accepts integers or returns integers. An implementation may therefore wrap the function. The wrapper checks arguments and results whenever the function is called.
This approach is related to software contracts, which monitor obligations at component boundaries.
Mutable values present further difficulties. A list may contain only integers when it first enters typed code, yet an untyped part of the program may retain another reference and later insert a string. Such aliasing means that checking the list only once may not protect later operations. Depending on the implementation, protection may require wrappers, checks at use sites, restrictions on mutation, or specialized runtime representations.
Blame
When a cast fails, merely reporting “type mismatch” may not identify which component violated an obligation. Blame assignment associates checks with boundaries and tracks responsibility for failures.
For function values, responsibility can change with the direction of data flow. A caller may provide an invalid argument, while a function implementation may return an invalid result.
Blame calculi formalize these relationships. Appropriate blame-safety results can establish that particular well-typed components are not held responsible for violations originating elsewhere. Such results depend on the specific calculus and enforcement mechanism; they are not automatic properties of every language offering optional type annotations.
Enforcement strategies
Gradual typing encompasses multiple implementation strategies.
Guarded or wrapper-based enforcement places monitors around values crossing typed–untyped boundaries. For higher-order values, these monitors continue checking later interactions. This can provide strong protection for typed components, but wrappers may affect performance, identity-sensitive operations, and interaction with existing libraries.
Transient enforcement checks relevant properties at operations within typed code rather than relying exclusively on persistent boundary wrappers. For example, a program may check that a value is callable before a call and check an expected result property afterward. The resulting guarantees differ from those of deep wrapper-based enforcement.
Optional or erased checking uses annotations for static analysis but does not insert corresponding runtime enforcement. Execution follows the underlying language’s runtime semantics. Such systems support incremental annotation and useful diagnostics, but unchecked values can violate the assumptions expressed by annotations.
These labels describe broad families rather than a universal classification. Hybrid implementations can combine strategies for different types or language features.
Formal guarantees
Gradual typing research studies several distinct correctness and usability properties.
Type safety
A runtime-enforced gradual language may satisfy a type-safety theorem: execution either produces a permitted result, continues indefinitely, or encounters an explicitly modeled error such as a failed cast, rather than reaching an undefined state caused by a type mismatch.
This does not mean that every accepted program executes without type errors. Gradual typing deliberately permits some uncertainty, and runtime cast failures are an expected possibility.
The exact theorem depends on the language. Exceptions, foreign code, unsafe operations, and mutable state may require additional assumptions.
The gradual guarantee
The gradual guarantee describes how program behavior should relate to changes in type precision.
Its static aspect generally requires that making annotations less precise should not turn an accepted program into a statically rejected one. Equivalently, adding precision may reveal errors that were previously hidden.
Its dynamic aspect generally requires that changing precision preserve the underlying computation, except for failures attributable to additional checking, according to a formally specified relation between executions.
This is a design criterion rather than a property implied merely by supporting an unknown type. Features such as overload resolution, conversions, and type-directed behavior can complicate or violate it.
Conservative behavior
A gradual extension of an existing static language may aim to preserve the original language’s typing and behavior for fully static programs. It may also aim to preserve the behavior of fully dynamic programs.
These goals must be checked separately. Their precise formulation depends on how the static and dynamic fragments are embedded in the combined language.
Formal models often use variants of lambda calculus and techniques from formal verification to establish these properties.
History and practical systems
Gradual typing builds on earlier work on dynamic types, casts, contracts, and interoperability between differently typed languages. Jeremy Siek and Walid Taha introduced the term and an influential formal treatment in their 2006 work, Gradual Typing for Functional Languages.
Subsequent research developed models for objects, mutable references, polymorphism, blame, and performance. Another direction, abstracting gradual typing, derives gradual type systems by interpreting imprecise types as descriptions of sets of more precise types, using ideas from abstract interpretation.
Practical systems illustrate different points in the design space:
- TypeScript supports incremental typing of JavaScript. Its
anytype permits extensive interaction with unchecked code, whileunknownrequires narrowing or other justification before many operations. TypeScript generally erases type annotations and does not automatically enforce them at runtime. It deliberately permits some statically unsound patterns. - Python supports optional type annotations and external static checking.
Anyis central to gradual checking in its typing ecosystem. The Python runtime does not ordinarily enforce annotations; separate tools or libraries are needed for runtime validation. - Typed Racket supports interaction between typed and untyped Racket modules. Its established deep enforcement model uses contracts at relevant boundaries, including monitoring of higher-order interactions.
Consequently, describing a language as “gradually typed” does not by itself specify its runtime guarantees. Academic usage often emphasizes formal semantics and enforcement, while practical usage frequently includes optional static checking with erased annotations.
Applications and limitations
Gradual typing is useful in software engineering when a complete conversion to static typing would be costly or disruptive. Typical applications include:
- introducing checked interfaces around existing dynamic libraries;
- annotating stable modules before rapidly changing ones;
- improving editor completion, navigation, and refactoring;
- documenting assumptions at API boundaries;
- detecting incompatible changes before execution.
The benefits depend on annotation coverage and checker configuration. A program can have many annotations while still passing most important values through unchecked types. Conversely, a smaller set of precise boundary annotations can expose substantial interface problems.
Runtime enforcement can impose significant costs, especially when higher-order values repeatedly cross boundaries. Wrappers can accumulate, and container checks can interact with mutation and identity. Cast composition and other optimization techniques can reduce some costs, but overhead depends on the program and implementation.
Erased systems avoid these particular runtime costs but cannot guarantee that external values satisfy their annotations. Type assertions and unchecked dynamic values may conceal errors rather than eliminate them.
Gradual typing also differs from type inference. Inference attempts to determine types automatically from program structure; gradual typing permits genuinely unknown information to remain. A language can support both. Nor is gradual typing synonymous with runtime data validation: validating an input establishes a particular property at a particular boundary, whereas gradual typing specifies how partial type information participates throughout a language’s checking and execution model.