1. What Is Type Checking?
Type checking is a core mechanism in programming language type systems. It is used to determine whether expressions, variables, function calls, and operations in a program satisfy type rules.
For example:
let age: number = 18;
age = "hello";
Here, the variable age is declared as type number, but it is assigned a string.
Type checking needs to determine:
- Whether the type of a variable assignment is compatible.
- Whether the types of function arguments match those of the parameters.
- Whether an operator supports the current operand types.
- Whether return values conform to the function declaration.
- Whether an object has the required properties and methods.
- Whether type conversions satisfy the language rules.
Depending on when checking occurs, it is usually divided into two categories:
| Dimension | Static Type Checking | Dynamic Type Checking |
|---|---|---|
| When checked | Before program execution | During program execution |
| What is checked | Source code and its type information | Values and operations during actual execution |
| Performed by | Compilers, static analyzers | Interpreters, virtual machines, or runtimes |
| Error detection | At compile time or analysis time | When the relevant code is executed |
| Type information | Usually has static type information | The runtime needs to identify the types of actual values |
| Typical languages | Java, C, C++, Rust, TypeScript | Python, JavaScript, Ruby, PHP |
| Main advantage | Detects type errors early | Flexible and suitable for dynamic operations at runtime |
| Main limitation | Some dynamic behavior is difficult to determine statically | Type errors may be delayed until runtime |
Note that static typing and dynamic typing describe type-checking mechanisms; they are not directly equivalent to strong typing and weak typing.
2. Static Type Checking
2.1 Basic Concepts
Static type checking means verifying, before program execution, through a compiler or static analysis tool, whether a program satisfies type rules based on the source code and type information.
It usually occurs during compilation, but this does not mean that all static type checking must be performed by a traditional compiler.
For example:
public class Main {
public static void main(String[] args) {
int age = 18;
age = "hello";
}
}
The Java compiler will detect the type mismatch at compile time and refuse to generate normal executable bytecode.
Core characteristics:
- Type errors can be found before the program runs.
- The compiler can verify constraints based on type information.
- Many illegal operations cannot pass compilation.
- Type information can assist with code completion, refactoring, and optimization.
- Some runtime errors still cannot be detected by static type checking.
2.2 Execution Mechanism of Static Type Checking
Static type checking usually goes through stages such as lexical analysis, syntax analysis, type information construction, and type checking.
Typical compilation process:
flowchart TD
A["Source Code"] --> B["Lexical Analysis"]
B --> C["Syntax Analysis"]
C --> D["Build AST"]
D --> E["Build Symbol Table"]
E --> F["Type Inference and Type Checking"]
F --> G{"Does Type Checking Pass?"}
G -->|"Pass"| H["Intermediate Representation Generation"]
G -->|"Fail"| I["Report Compilation Error"]
H --> J["Subsequent Compilation and Code Generation"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The stage divisions and execution order in actual compilers may differ. For example, type checking and intermediate representation construction may be interleaved.
2.3 Core Principles of Type Checking
Static type checking is not simply about determining what type a variable is declared as; rather, it infers the types of expressions according to type rules and verifies whether operations are legal.
For example:
int a = 10;
int b = 20;
int result = a + b;
The compiler can infer:
a : int
b : int
a + b : int
result : int
The expression satisfies the integer addition rules, so the type check passes.
Now consider an incorrect example:
int a = 10;
String b = "20";
int result = a + b;
The compiler finds that:
- The type of
aisint. - The type of
bisString. a + bdoes not satisfy the integer addition rules in Java.- The result of the expression cannot be assigned to
int.
Therefore, a type error is reported at the compilation stage.
2.4 Type Inference
Static type checking does not mean that every variable must have its type explicitly declared.
Type inference allows the compiler to deduce types from expressions and context.
For example, in Rust:
fn main() {
let age = 18;
let price = 19.99;
println!("{}", age);
println!("{}", price);
}
The compiler can infer:
age : i32
price : f64
Java:
var name = "Alice";
var age = 18;
The compiler infers String and int respectively.
TypeScript:
let count = 10;
count = 20;
count = "hello"; // type error
Although number is not written explicitly, TypeScript can still infer the variable's type from its initial value.
Therefore:
Static type checking is not the same as explicit type declaration; type inference is likewise an important capability of a static type system.
2.5 Advantages of Static Type Checking
1. Finding errors early
function add(a: number, b: number): number {
return a + b;
}
add(10, "20"); // type check fails
An argument type mismatch can be found without ever running the function call.
2. Improving code maintainability
Type declarations can serve as code contracts, making a function's inputs, outputs and data structures explicit.
interface User {
id: number;
name: string;
email: string;
}
function getUser(): User {
return {
id: 1,
name: "Alice",
email: "alice@example.com"
};
}
Callers can know exactly what data structure getUser() returns.
3. Enabling compile-time optimization
With more type information at its disposal, a compiler can perform type specialization, eliminate unnecessary checks and apply other optimizations.
However, the specific optimization capabilities depend on the language, compiler and runtime; one cannot assume that static typing necessarily means a faster program.
4. Improving the development tooling experience
Static type information can support:
- Intelligent code completion.
- Parameter hints.
- Type navigation.
- Safe refactoring.
- Analysis of unused variables and unreachable code.
- Checking interface implementations.
2.6 Limitations of Static Type Checking
Static type checking can only verify properties that the analyzer can infer and prove.
For example:
public class Main {
public static void main(String[] args) {
String value = null;
System.out.println(value.length());
}
}
The code compiles successfully in Java, but a NullPointerException occurs at runtime.
The reasons are:
- The static type of
valueisString. nullcan be assigned to a reference type.- Ordinary Java type checking does not guarantee that the reference is non-null at the point of the call.
- When the method call is actually executed, the runtime finds that the reference is null.
This shows that:
Passing static type checking does not mean a program is free of runtime errors.
Other problems that are hard to catch with ordinary static type checking alone include:
- Array index out of bounds.
- Division by zero.
- File not found.
- Network request failure.
- Concurrency races.
- Business logic errors.
- External data not matching expectations.
III. Dynamic Type Checking
3.1 Basic Concepts
Dynamic type checking means that while a program is running, it decides whether the current operation is legal based on the type of the actual value.
In dynamically typed languages, variables usually do not need to be fixed to a single type when they are declared.
For example, in Python:
value = 10
value = "hello"
value = [1, 2, 3]
The same variable can reference objects of different types at different times.
The variable name itself does not have to be permanently bound to one type; the actual type is determined by the value it currently references.
But this does not mean dynamically typed languages have no type system. Languages such as Python and JavaScript also have complete type rules; it is just that many type constraints are enforced at runtime.
3.2 How Dynamic Type Checking Is Executed
Take Python as an example:
def add(a, b):
return a + b
print(add(10, 20))
print(add("hello", "world"))
print(add(10, "world"))
The first two calls execute normally.
The third call raises a TypeError when the addition operation is performed.
Typical execution process:
flowchart TD
A["Load program"] --> B["Execute statement"]
B --> C["Read actual runtime value"]
C --> D["Get object type information"]
D --> E["Type-check the operation"]
E --> F{"Is the operation valid?"}
F -->|"valid"| G["Execute operation"]
F -->|"invalid"| H["Raise runtime type error"]
G --> I{"Any following statements?"}
I -->|"yes"| B
I -->|"no"| J["Program ends"]
H --> K["Propagate or handle exception"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style K fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The core process includes:
- Obtain the actual values currently involved in the operation.
- Determine the runtime types of the values.
- Determine whether the operation is valid according to the type rules.
- If it is valid, execute the operation.
- If it is invalid, raise an exception or produce a runtime error.
3.3 Typical Examples of Dynamic Type Checking
Python:
value = 100
print(value + 20)
value = "100"
print(value + 20)
The second addition raises a TypeError.
JavaScript:
let value = 100;
console.log(value + 20);
value = "100";
console.log(value + 20);
Output:
120
10020
JavaScript's + operator supports both numeric addition and string concatenation, so no type error is raised here.
If you execute:
let value = "hello";
value.toFixed(2);
then a runtime TypeError occurs because a string has no toFixed method.
This shows that dynamic type checking involves not only variable types, but also the semantic rules of specific operators, methods, and property access.
3.4 Advantages of Dynamic Type Checking
1. Flexible coding
A variable can reference values of different types at different stages, which suits dynamic data processing and flexible data structures.
2. Well suited to dynamic language features
For example:
- Dynamic attribute access.
- Runtime reflection.
- Dynamic method invocation.
- Metaprogramming.
- Plugin loading.
- Dynamic object composition.
3. Well suited to rapid development
In some scenarios, it can reduce explicit type declarations and type modeling work.
4. Supports runtime polymorphism
At runtime, the corresponding operation is selected based on the actual object type, enabling flexible object behavior.
3.5 Limitations of dynamic type checking
1. Errors may surface late
def process_user(user):
return user.name.upper()
process_user({"name": "Alice"})
Only when execution reaches user.name does the program discover that the dictionary object has no such attribute, raising an AttributeError.
2. Greater pressure on test coverage
If a function accepts data of multiple types, tests must cover more type combinations and edge cases.
3. Code contracts are less intuitive
Without type annotations or documentation, callers may be unable to determine a function's input and output constraints directly.
4. Higher refactoring risk
Variable types and object structures may change during execution, so modifying one data structure can affect multiple call sites.
4. Core Differences Between Static Checking and Dynamic Checking
The two are not mutually exclusive; they differ in when type checking occurs and what information it relies on.
| Comparison dimension | Static type checking | Dynamic type checking |
|---|---|---|
| Checking time | Before execution | At runtime |
| Basis for types | Type declarations, inference, static rules | Actual runtime values and runtime rules |
| Error exposure | Compilation or static analysis phase | When the relevant operation is executed |
| Reliance on testing | Still required | Usually relies more on test coverage |
| Dynamic behavior | Requires additional type modeling or runtime boundary checks | Native support for more dynamic behavior |
| Developer experience | Type hints and refactoring support are usually stronger | Flexible coding, but type constraints may be less explicit |
| Performance impact | Checking mainly occurs before execution, but runtime checks may still exist | Type checks may enter the runtime path |
| Representative languages | Java, C++, Rust, TypeScript | Python, JavaScript, Ruby |
4.1 Static typing does not mean the absence of dynamic checks
Java is a statically typed language, but dynamic checks are still required at runtime.
For example:
Object value = "hello";
if (value instanceof String) {
String text = (String) value;
System.out.println(text.length());
}
The compiler knows that the static type of value is Object.
But the object it actually references may be a String, an Integer, or some other type.
instanceof determines the object's actual type at runtime.
Consider array covariance:
Object[] values = new String[2];
values[0] = "hello";
values[1] = 100;
Although the variable's static type is Object[], the actual array object is a String[].
The second assignment throws an ArrayStoreException at runtime.
This shows that:
Static type checking and dynamic type checking can coexist in the same language.
4.2 Dynamically typed languages can also undergo static checking
Python itself is a dynamically typed language, but type annotations and static analysis tools can catch type problems in advance.
For example:
def add(a: int, b: int) -> int:
return a + b
result = add(10, "20")
By default, the Python interpreter will not refuse to execute this code before the call because of its type annotations.
However, static analysis tools such as MyPy and Pyright can detect the argument type mismatch.
Therefore, it is necessary to distinguish between:
- A language's own type enforcement mechanism.
- Capabilities provided by external static type analysis tools.
- The type checks actually performed at runtime.
Type annotations themselves do not necessarily have runtime enforcement power.
4.3 Static vs. dynamic type checking is not the same distinction as strong vs. weak typing
This is a very easily confused concept.
Static and dynamic typing mainly describe when type checking occurs.
Strong and weak typing, on the other hand, are usually used to discuss whether a language permits implicit conversion when types are incompatible, and whether type boundaries are easily bypassed. However, "strong typing" and "weak typing" have no unified, strict formal definition, so any practical comparison must specify the concrete rules.
For example:
| Language | Type checking characteristics | Other type features |
|---|---|---|
| Java | Primarily static checking | Relatively strict type constraints, with automatic type conversion |
| Rust | Primarily static checking | Strict type constraints, emphasizing type safety |
| Python | Primarily dynamic checking | Does not automatically add a string and an integer together |
| JavaScript | Primarily dynamic checking | Has many implicit type conversions |
| TypeScript | Primarily static checking | Type information is usually erased after compilation; at runtime it still follows JavaScript semantics |
One cannot simply assume that:
- A statically typed language is a strongly typed language.
- A dynamically typed language is a weakly typed language.
- If static checking passes, there are no runtime type errors.
- A dynamically typed language has no static type analysis capability at all.