Back to series
· 10 min read

Type Safety and Type Erasure


I. Type Safety

1. What Is Type Safety

Type safety means that, under the constraints of type rules, a program can operate on data in ways permitted by the type system and avoid operations that violate type semantics.

For example:

let age: number = 25;

age = 30;       // valid
age = "hello";  // type error

TypeScript's static type checking can detect that the second assignment violates the type constraint declared for the variable.

The core issues that type safety focuses on include:

  • Whether data is used according to the correct type.
  • Whether operations conform to type rules.
  • Whether function parameters and return values satisfy their contracts.
  • Whether object access conforms to structural constraints.
  • Whether type conversions have clear semantics.
  • Whether the program may produce type-related runtime errors.

Note that type safety does not mean a program will never go wrong. It mainly constrains type-related errors and cannot automatically guarantee that business logic, algorithms, concurrency, resource management, and other aspects are all correct.

2. Basic Goals of Type Safety

A type system usually aims to guarantee the following properties:

Goal Meaning Example
Type consistency Data use conforms to its declared type A numeric variable does not accept a string assignment
Operation validity Operations conform to type definitions Do not perform undefined numeric operations on ordinary objects
Interface consistency Function calls conform to parameter and return value contracts The number and types of arguments are correct
Memory safety Avoid illegal memory access Prevent dangling references and out-of-bounds access
State constraints Data is in an allowed type state Restrict state values through enums

Among these, type safety is closely related to memory safety, but they are not the same concept.

For example:

  • Rust's type system and ownership mechanism together provide strong memory safety guarantees.
  • Java reduces many memory error risks through runtime type checking, reference management, and garbage collection.
  • C allows extensive low-level memory operations, so even if a program compiles, out-of-bounds access and undefined behavior may still occur.

3. Type Errors and Runtime Errors

A type error is an illegal operation that the type system can identify.

function add(a: number, b: number): number {
  return a + b;
}

add(10, 20);       // valid
add(10, "hello");  // type error

Runtime errors may come from many causes:

const user = JSON.parse('null');

console.log(user.name);

This code can pass TypeScript compilation because the type returned by JSON.parse is usually any. But accessing null.name at runtime will fail.

This shows that:

  • Static type checking does not necessarily cover all runtime data.
  • Dynamic data must undergo runtime validation.
  • Using escape hatches such as any may weaken type-checking capabilities.

The actual effectiveness of type safety depends on the language's type system, compiler checking rules, runtime mechanisms, and whether the program bypasses type constraints.

II. Theoretical Foundations of Type Safety

Type safety is not only an engineering practice concept but also an important research topic in programming language theory.

1. Typing Judgment

Type systems usually use typing judgments to express that an expression has a certain type.

Common form:

\Gamma \vdash e : T

Where:

  • \Gamma: the typing environment, recording variables and their types.
  • e: an expression.
  • T: the type of the expression.
  • \vdash: indicates that a typing judgment can be derived under the given environment.

For example:

\Gamma = \{x : Int\}

Then we can derive:

\Gamma \vdash x : Int

If:

\Gamma \vdash x : Int
\Gamma \vdash y : Int

And if the integer addition rule requires both operands to be integers, then:

\Gamma \vdash x+y : Int

A type system determines whether an expression is valid through a set of derivation rules.

2. Typing Rules

Typing rules specify how different syntactic structures acquire types.

For example, function application can be abstracted as:

\frac{ \Gamma \vdash f : A \rightarrow B \quad \Gamma \vdash x : A }{ \Gamma \vdash f(x) : B }

It means:

  • The function f has type A \rightarrow B.
  • The parameter x has type A.
  • Therefore, the result type of the function call f(x) is B.

If the argument type does not conform to the function's requirement, type inference cannot be completed under this rule.

3. Type Soundness

Type soundness is a core property in type system theory.

It is usually described by two important properties:

  • Progress: A well-typed expression is either already a value or can continue to evaluate.
  • Preservation: After an expression takes one evaluation step, its type remains unchanged.

Progress

Suppose:

\varnothing \vdash e : T

Then for a closed, well-typed expression, it is either already a value or a next evaluation step exists.

Intuitively, a program will not fall into certain illegal computational states due to a type mismatch.

Preservation

If:

\Gamma \vdash e : T

and:

e \rightarrow e'

then:

\Gamma \vdash e' : T

That is, after the expression takes one evaluation step, its type still satisfies the original type constraint.

Relationship to Type Soundness

flowchart TB
    A["Type System Definition"] --> B["Type Rules"]
    B --> C["Type Checking"]
    C --> D["Well-Typed Expression"]
    D --> E["Progress"]
    D --> F["Preservation"]
    E --> G["Type Soundness"]
    F --> G

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Note that progress and preservation are properties defined for a particular formal language and its operational semantics. Real programming languages may include reflection, foreign functions, undefined behavior, unsafe interfaces, and dynamic type escape mechanisms, so one cannot assert that an entire language implementation satisfies type soundness under some simple model merely because the language has static types.

III. Implementation Methods for Type Safety

Different languages use different mechanisms to achieve type safety.

1. Static Type Checking

Static type checking mainly occurs before program execution.

For example, Java:

int age = 25;

age = 30;        // valid
age = "hello";   // compile error

The compiler checks the program based on variable declarations, expression types, and type rules.

Typical languages:

  • Java
  • C#
  • Rust
  • Go
  • C++
  • TypeScript

Static type checking can catch many type errors in advance, but it does not mean that runtime type checking is unnecessary.

2. Dynamic Type Checking

Dynamically typed languages usually determine the actual type of an object at runtime and check whether an operation is valid when it is performed.

For example, Python:

def add(a, b):
    return a + b

print(add(10, 20))
print(add(10, "hello"))

The second call will raise a TypeError at runtime.

Dynamic typing does not mean that there is no type system; rather, type constraints are more often enforced at runtime.

3. Combining Static and Dynamic Checking

Modern languages often use both mechanisms at the same time.

For example, Java:

Object value = "hello";

String text = (String) value;  // valid

Integer number = (Integer) value; // runtime ClassCastException

The compiler allows Object to be explicitly cast to Integer, because such a cast is possible in the type hierarchy.

But the object is actually a String at runtime, so the cast fails.

This reflects the responsibilities of the two phases:

  • Check at compile time whether the cast is valid.
  • Check at runtime whether the object's actual type meets the cast requirement.

4. Type Safety Checking Process

flowchart TB
    A["Write source code"] --> B["Parsing and type analysis"]
    B --> C{"Static type check passes"}
    C -->|"No"| D["Report compilation errors"]
    C -->|"Yes"| E["Generate executable code"]
    E --> F["Program execution"]
    F --> G["Perform runtime type checking"]
    G --> H{"Runtime type meets requirements"}
    H -->|"Yes"| I["Continue execution"]
    H -->|"No"| J["Type-related runtime exception"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style J fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

IV. What Is Type Erasure

1. Definition of Type Erasure

Type Erasure is a compile-time or runtime implementation mechanism in which some type information in a program is removed, weakened, or no longer retained as independent runtime type information at a certain stage.

It often appears in generic implementations.

For example, in Java:

List<String> names = new ArrayList<>();
names.add("Alice");

The Java compiler checks the generic constraints of List<String>.

But in traditional Java generic implementations, what the JVM runtime mainly sees is:

List names = new ArrayList();

The generic parameter String is not retained as independent generic parameter information of an ordinary object in the runtime type structure of a traditional object instance.

This is a typical manifestation of Java generic type erasure.

Note the following:

  • Type erasure does not mean that all type information disappears.
  • Different languages have different type erasure mechanisms.
  • Type information may still exist in metadata, signatures, debugging information, or runtime description structures.
  • Type erasure is not the same as removing all type checks.

2. Why Type Erasure Is Needed

Type erasure is not simply about reducing code.

The design of Java generics needed to take historical compatibility into account.

Early versions of Java did not have generics, and collections mainly stored objects through Object.

For example:

List list = new ArrayList();

list.add("Alice");
list.add(100);

String name = (String) list.get(0);

This design had several problems:

  • Collections could mix data of different types.
  • Retrieving elements required explicit type casting.
  • Type errors might be exposed only at runtime.

After Java 5 introduced generics:

List<String> list = new ArrayList<>();

list.add("Alice");
// list.add(100); // compile error

String name = list.get(0);

The compiler checks generic constraints at compile time and inserts type casts where necessary.

While maintaining the JVM runtime compatibility model, Java adopted the type erasure mechanism.

Its core goals include:

  1. Give generic code stronger type constraints at compile time.
  2. Be as compatible as possible with older JVM versions and non-generic bytecode.
  3. Avoid generating a separate runtime class for every combination of generic parameters.

V. Type Erasure Mechanism in Java Generics

Java is the most typical language for understanding type erasure.

1. Generic Parameter Erasure

For example:

class Box<T> {
    private T value;

    public void set(T value) {
        this.value = value;
    }

    public T get() {
        return value;
    }
}

After compilation, the generic parameter T is usually erased to its upper bound.

If no upper bound is explicitly specified:

T

Its default upper bound is:

Object

So its core effect can be understood as:

class Box {
    private Object value;

    public void set(Object value) {
        this.value = value;
    }

    public Object get() {
        return value;
    }
}

This is a conceptual illustration, not a complete Java compiler decompilation result.

2. Erasure of Bounded Type Parameters

If an upper bound is specified:

class NumberBox<T extends Number> {
    private T value;
}

Then after erasure, T corresponds to its first upper bound, Number.

Conceptually:

class NumberBox {
    private Number value;
}

For example:

NumberBox<Integer> integerBox;
NumberBox<Double> doubleBox;

At runtime, both use the same generic class body; no two separate class definitions, NumberBox<Integer> and NumberBox<Double>, are generated.

3. The Compiler Inserts Type Casts

For example:

List<String> names = new ArrayList<>();

names.add("Alice");

String name = names.get(0);

After generic erasure, the erased return type of List.get() is Object.

The compiler inserts a type cast wherever one is needed.

Conceptually:

List names = new ArrayList();

names.add("Alice");

String name = (String) names.get(0);

The actual bytecode can be inspected with the following commands:

javac Example.java
javap -c -s Example

Where:

  • -c displays the bytecode instructions.
  • -s displays the method descriptors.

You can observe the type cast instructions generated by the compiler, such as checkcast.

4. Comparison Before and After Type Erasure

Comparison Dimension Source Code Stage Runtime Model After Erasure
Generic class Box<String> Box
Generic parameter T Upper bound type
Unbounded parameter T Object
Bounded parameter T extends Number Number
Generic method <T> T get() Object get(), depending on the erasure rules
Type checking Generic constraints checked at compile time Mainly relies on the erased types and necessary runtime checks

5. The Complete Process of Type Erasure

flowchart TB
    A["Java generic source code"] --> B["Generic type checking"]
    B --> C["Type erasure"]
    C --> D["Erase type parameters"]
    C --> E["Insert casts at necessary locations"]
    C --> F["Generate bridge methods"]
    D --> G["Generate bytecode"]
    E --> G
    F --> G
    G --> H["JVM loading and execution"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

6. Limitations Caused by Type Erasure

1. Cannot Directly Create Instances of Generic Type Parameters

The following code does not compile in Java:

class Factory<T> {
    public T create() {
        return new T();
    }
}

The reason is that, after type erasure, the compiler cannot determine from the erased type parameter T which concrete class to instantiate.

A common solution is to pass in Class<T>:

class Factory<T> {
    private final Class<T> type;

    Factory(Class<T> type) {
        this.type = type;
    }

    public T create() throws Exception {
        return type.getDeclaredConstructor().newInstance();
    }
}

This approach requires the type to have an accessible no-argument constructor; reflective instantiation may also be affected by access permissions, abstract classes, constructor exceptions, and other factors.

2. Cannot Directly Create Generic Arrays

The following code does not compile:

class Container<T> {
    T[] values = new T[10];
}

Because T is erased at runtime, the JVM cannot directly create a generic array with an unknown component type.

Common alternatives:

class Container<T> {
    private final Object[] values;

    Container(int size) {
        values = new Object[size];
    }
}

Or use reflection:

@SuppressWarnings("unchecked")
T[] createArray(Class<T> type, int size) {
    return (T[]) java.lang.reflect.Array
        .newInstance(type, size);
}

The cast here relies on the passed-in Class<T> being consistent with the array component type; in real-world projects, type boundaries still need to be handled carefully.

3. Cannot Overload Methods Based on Generic Parameters

The following code does not compile in Java:

void process(List<String> values) {}

void process(List<Integer> values) {}

The reason is that both have the same method parameter type after erasure:

void process(List values) {}

This results in a method signature conflict.

4. Cannot Directly Use instanceof to Check Full Generic Type Parameters

The following code does not compile in Java:

if (value instanceof List<String>) {
    // ...
}

Because at runtime, it is impossible to directly check whether an object is a List<String>.

You can check the raw type:

if (value instanceof List<?>) {
    // ...
}

If you need to confirm the element type, you must iterate over the elements and perform runtime checks, or use a dedicated data validation mechanism.

5. Type Erasure and Bridge Methods (Bridge Method)

Bridge methods are synthetic methods generated by the Java compiler to preserve generic inheritance and polymorphism semantics.

For example:

class Parent<T> {
    public void set(T value) {}
}

class Child extends Parent<String> {
    @Override
    public void set(String value) {}
}

After erasure: