Back to series
· 12 min read

Generics & Type Systems


I. What Is a Type System?

A type system is a set of mechanisms that a programming language uses to define, organize, and constrain data types and the rules for operating on them.

It specifies:

  • What type a value belongs to.
  • What type of data a variable can store.
  • Which operations can be applied to a given type.
  • Whether different types can be converted into one another.
  • What types of arguments a function accepts and what type of result it returns.
  • How type errors in a program are detected and handled.

For example:

let age: number = 25;
let name: string = "Alice";

age = "hello"; // type error

TypeScript's type system recognizes that age is being assigned a string and reports an error during the compile-time check.

The core goal of a type system is to constrain program behavior before or during execution and to catch as many operations that violate type rules as possible.

1. What Is a Type?

A type can be understood as a set of values together with the constraints on the operations allowed on them.

For example:

Type Typical values Allowed operations
Integer 10, -5 Addition, subtraction, multiplication, division, comparison
String "hello" Concatenation, slicing, searching
Boolean true, false Logical operations
Array [1, 2, 3] Indexing, iteration, appending
Function Function object Calling, passing, returning
Object {name: "Tom"} Property access, modification

A type describes not only how data is stored but also what operations a program can perform on it.

For example, integers can undergo arithmetic operations, and strings can undergo text operations. A type system uses rules to restrict unreasonable operations.

2. Main Responsibilities of a Type System

A type system generally covers the following aspects:

Responsibility Description
Type definition Defines primitive types, composite types, and user-defined types
Type checking Checks whether expressions, variables, and functions conform to type rules
Type inference Automatically infers the type of an expression from context
Type conversion Defines the rules for converting between different types
Type compatibility Determines whether one type can be used where another type is required
Type constraints Restricts the range of values for generic parameters or type variables

II. Main Categories of Type Systems

Type systems can be classified along several dimensions, though these dimensions are not entirely mutually exclusive.

For example, static typing and dynamic typing describe when type checking occurs; strong typing and weak typing describe type rules and conversion behavior; nominal typing and structural typing describe how type compatibility is determined.

1. Static Typing vs. Dynamic Typing

Static Typing

Statically typed languages perform type checking primarily at compile time or during static analysis.

int age = 25;
String name = "Alice";

age = "hello"; // compile error

Key characteristics:

  • Type errors can be found before runtime.
  • Variables, expressions, and functions usually carry type information that can be analyzed.
  • The compiler can use type information for optimization.
  • Type constraints help with tooling hints and code refactoring.

Typical languages: Java, C, C++, Go, Rust, TypeScript.

Note that TypeScript's type checking happens at compile time, but the JavaScript runtime does not retain the full TypeScript type system.

Dynamic Typing

Dynamically typed languages typically determine or check the types of values at runtime.

value = 100
value = "hello"

The same variable can reference objects of different types at different times.

Key characteristics:

  • Writing code is more flexible.
  • Type errors usually surface during execution.
  • Runtime type checking is required.
  • Code analysis and refactoring may depend more heavily on tooling and tests.

Typical languages: Python, JavaScript, Ruby, PHP.

Core differences:

Dimension Static Typing Dynamic Typing
Type checking Compile time or static analysis phase Mainly at runtime
Type errors Some errors can be detected in advance Usually discovered when the relevant operation is executed
Type information Usually has explicit static type information Runtime objects have type information
Flexibility Type constraints are relatively explicit Runtime behavior is more flexible
Tooling support Usually facilitates static analysis and refactoring Depends on runtime information and analysis tools

Note: static typing does not mean there is no type checking at runtime, and dynamic typing does not mean there are no type constraints.

2. Strong Typing and Weak Typing

Strong typing and weak typing describe the degree to which a language constrains type rules, type conversions, and mixed-type usage.

There is no strict, unified standard for these two concepts that applies to all languages.

For example:

console.log("5" + 1); // "51"
console.log("5" - 1); // 4

JavaScript performs different implicit type conversions depending on the operator.

Now look at Python:

print("5" + 1)  # TypeError

Python does not allow this kind of addition operation directly between a string and an integer.

Things to note:

  • Strong typing is not equivalent to static typing.
  • Weak typing is not equivalent to dynamic typing.
  • The existence of implicit type conversion is not sufficient on its own to determine that a language is weakly typed.
  • Different operations and different contexts may use different type conversion rules.

3. Nominal Typing and Structural Typing

This is a very important dimension for understanding modern type systems.

Nominal Typing

Type compatibility is determined by the name of the type declaration and its inheritance or implementation relationships.

For example, Java:

interface Flyable {
    void fly();
}

class Bird implements Flyable {
    public void fly() {}
}

Bird can be used as Flyable because it explicitly declares that it implements that interface.

Structural Typing

Compatibility is determined based on the member structure that a type actually has.

For example, TypeScript:

type Point = {
    x: number;
    y: number;
};

function printPoint(point: Point) {
    console.log(point.x, point.y);
}

const position = {
    x: 10,
    y: 20,
    z: 30
};

printPoint(position);

position is not explicitly declared as Point, but it has the members required by Point, so it can satisfy the requirements of that structural type.

Comparison Nominal Typing Structural Typing
Basis for determination Type name and declaration relationships Type member structure
Whether explicit declaration is required Usually required Usually not required
Flexibility Relatively explicit Relatively flexible
Typical languages Java, C# TypeScript, Go (interface implementation uses implicit structural matching)

Go's interface implementation is structural, but Go's concrete type declarations and other type relationships do not mean that the entire language is a purely structural type system.

III. What Are Generics?

Generics is a parameterized type mechanism that allows developers to define classes, interfaces, functions, and data structures independent of specific data types.

Its core idea is:

Treat types as parameters so that code can work with multiple types while retaining type constraints.

1. Why Are Generics Needed?

Suppose you need to write a function that returns the first element in an array.

Without generics, you might need to write separate functions for different types:

int firstInt(int[] values) {
    return values[0];
}

String firstString(String[] values) {
    return values[0];
}

double firstDouble(double[] values) {
    return values[0];
}

The business logic of these functions is exactly the same; only the data types they handle differ.

This leads to:

  • Duplicate code.
  • Increased maintenance costs.
  • Difficulty extending to new types.
  • General-purpose data structures are difficult to design.

Generics can solve this problem.

2. Using Generics to Achieve Type Reuse

Java example:

public class Box<T> {
    private T value;

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

    public T get() {
        return value;
    }
}

Usage:

Box<Integer> intBox = new Box<>();
intBox.set(100);

Integer value = intBox.get();

Here, T is a type parameter.

When creating Box<Integer>, T corresponds to Integer.

When creating Box<String>, T corresponds to String.

Generics allow the same code to work with multiple types without needing to reimplement it for each type.

3. Core Components of Generics

Concept Meaning Example
Type parameter A type placeholder used in a definition T, E, K, V
Type argument The concrete type passed in when using generics String, Integer
Generic class A class defined using type parameters Box<T>
Generic interface An interface defined using type parameters Repository<T>
Generic method A method that declares its own type parameters <T> T identity(T value)
Type constraint Restricts the types that a type parameter can accept T extends Number

Common naming conventions:

  • T: Type, representing a general type.
  • E: Element, representing a collection element.
  • K: Key, representing a key.
  • V: Value, representing a value.
  • N: Number, representing a numeric type.
  • R: Return, representing a return type.

These are only conventions, not rules enforced by the language.

IV. Implementation Approaches for Generics

1. Generic Functions

Generic functions allow a function to handle data of different types while preserving the type relationship between parameters and return values.

TypeScript example:

function identity<T>(value: T): T {
    return value;
}

const numberValue = identity<number>(100);
const stringValue = identity<string>("hello");

Here:

  • T is a type parameter.
  • value: T indicates that the parameter type is T.
  • : T indicates that the return type is also T.

When calling the function, you can explicitly pass the type argument:

identity<number>(100);

You can also let the compiler infer it automatically:

identity(100);

In this case, the compiler infers from the argument 100 that T is number.

2. Generic Classes

Generic classes can apply type parameters to member variables, constructors, and methods.

class Box<T> {
    private value: T;

    constructor(value: T) {
        this.value = value;
    }

    getValue(): T {
        return this.value;
    }
}

const numberBox = new Box<number>(100);
const stringBox = new Box<string>("hello");

Generic classes are especially suitable for building:

  • Containers.
  • Collections.
  • Caches.
  • Data access objects.
  • Message queues.
  • General-purpose business models.

3. Generic Interfaces

Generic interfaces are used to define behavioral constraints with type parameters.

interface Repository<T> {
    findById(id: number): T | null;
    save(entity: T): void;
}

Different business objects can reuse the same interface:

interface User {
    id: number;
    name: string;
}

interface Product {
    id: number;
    price: number;
}

const userRepository: Repository<User>;
const productRepository: Repository<Product>;

Generic interfaces can decouple concrete data models from common operations.

4. Multiple Type Parameters

Generics can accept multiple type parameters at the same time.

class Pair<K, V> {
    constructor(
        public key: K,
        public value: V
    ) {}
}

const pair = new Pair<string, number>("age", 25);

K and V represent the types of the key and value, respectively.

Common applications include:

  • Key-value mappings.
  • Dictionaries.
  • Generic result objects.
  • Request and response models.
  • Multi-type composite structures.

V. Generic Constraints

Although generics support type parameterization, this does not mean that a type parameter can perform arbitrary operations in any situation.

If a generic function needs to access a property or call a method, it must ensure that the type parameter has the corresponding capability.

1. Why Are Constraints Needed?

For example:

function getLength<T>(value: T): number {
    return value.length;
}

This code has a type problem.

Because T can represent any type, the compiler cannot guarantee that all types have a length property.

For example:

  • Strings have length.
  • Arrays have length.
  • Numbers do not have length.

Therefore, a constraint needs to be added.

2. Using extends to Define Constraints

interface HasLength {
    length: number;
}

function getLength<T extends HasLength>(value: T): number {
    return value.length;
}

Here:

T extends HasLength means that the type parameter T must satisfy the structural requirements of HasLength.

Therefore, types such as strings and arrays that have a length property can all be used.

getLength("hello");
getLength([1, 2, 3]);

But numbers do not satisfy the constraint:

getLength(100); // Type error

3. Upper-Bound Constraints and Capability Constraints

Different languages express generic constraints in different ways.

Java:

public <T extends Number> double sum(T a, T b) {
    return a.doubleValue() + b.doubleValue();
}

Here T must be Number or a subclass of it.

TypeScript:

function printName<T extends { name: string }>(value: T) {
    console.log(value.name);
}

Here T must have a name: string property.

Rust:

fn print_value<T: std::fmt::Display>(value: T) {
    println!("{}", value);
}

Here T must implement the Display trait.

The essence of these constraints is that generic code depends only on the capabilities explicitly provided by the type parameter, not on all the implementation details of a specific type.

4. Multiple Constraints

Some languages allow a single type parameter to satisfy multiple constraints at the same time.

Java:

public <T extends Number & Comparable<T>> T max(T a, T b) {
    return a.compareTo(b) >= 0 ? a : b;
}

Here T must:

  • Extend Number.
  • Implement Comparable<T>.

TypeScript:

interface Named {
    name: string;
}

interface Identifiable {
    id: number;
}

function printEntity<T extends Named & Identifiable>(value: T) {
    console.log(value.id, value.name);
}

Rust:

fn print_value<T: std::fmt::Display + Clone>(value: T) {
    println!("{}", value.clone());
}

Multiple constraints allow generic code to rely on multiple well-defined type capabilities.

6. Type Inference

Type inference is the process by which a compiler or type checker automatically determines types based on expressions, variables, and context.

It reduces explicit type declarations while preserving type-checking capabilities.

1. Assignment-Based Type Inference

TypeScript:

let count = 100;

Based on the initial value, the compiler can infer:

let count: number = 100;

Rust:

let count = 100;

The compiler usually infers it as the default integer type i32, unless the context provides other type information.

2. Generic Type Inference

function identity<T>(value: T): T {
    return value;
}

const result = identity(100);

Type inference process:

flowchart TD
    A["Call identity(100)"] --> B["Analyze argument type"]
    B --> C["Get number"]
    C --> D["Infer type parameter T"]
    D --> E["T = number"]
    E --> F["Determine function parameter type"]
    F --> G["Determine return type"]
    G --> H["result type is number"]

    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:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

3. Contextual Type Inference

Type inference does not necessarily depend only on function parameters; it may also depend on variable declarations, return-value context, and expression combinations.

For example, TypeScript:

const numbers: number[] = [1, 2, 3];

numbers.map(item => item * 2);

Based on the type of numbers, the compiler can infer:

  • item is number.
  • The result of item * 2 is number.
  • map returns a number[].

This mechanism is called contextual typing.

4. Type Inference Is Not Dynamic Typing

This is a common point of confusion.

Type inference only reduces explicit declarations; it does not mean that a type can change freely at runtime.

For example:

let value = 100;

value = 200;      // valid
value = "hello";  // type error

After the compiler infers value as number, it still enforces type constraints.

Therefore:

  • Type inference addresses how types are determined.
  • Static typing addresses when types are checked.
  • Dynamic typing addresses how types are determined and checked at runtime.

These three belong to different dimensions.

7. Type Erasure and Reified Generics

There are important differences in how generics are implemented across languages.

In particular, it is important to understand type erasure and reified generics.

1. What Is Type Erasure?

Java generics use type erasure.

During compilation, the compiler uses generic information for type checking and erases most generic type parameter information when generating bytecode.

For example:

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

Looking at the generic source code, they are different parameterized types.

But at Java runtime, both usually exist as the List type.

This can be understood as:

List names = new ArrayList();
List numbers = new ArrayList();

This is only a conceptual simplification; it does not mean the actual compilation process simply deletes all generic syntax. The compiler may also insert type casts and retain some generic metadata through bytecode signatures.

Main characteristics of type erasure:

  • Generic type parameters are usually not retained as ordinary runtime type information.
  • The compiler is responsible for performing generic type checking.
  • Type casts are inserted when necessary.
  • At runtime, it is usually impossible to directly determine whether an object is List<String>.

For example:

if (value instanceof List<String>) {
    // Java does not allow this kind of direct check
}

Because at runtime, it is usually impossible to distinguish List<String> from List<Integer>.

2. Reasons for and Impacts of Type Erasure

When Java generics were designed, compatibility with existing non-generic code was required.

Type erasure enables generics to maintain good compatibility with older Java bytecode and the existing collections system.

But it also brings some limitations:

Limitation 1: Cannot directly create instances of type parameters

class Box<T> {
    T value;

    // T item = new T(); // not allowed
}

Because at runtime, the specific type of T is usually unknown.

Limitation 2: Cannot directly create generic arrays

// T[] values = new T[10]; // not allowed

Limitation 3: Cannot overload methods with different generic parameters

// void process(List<String> values) {}
// void process(List<Integer> values) {}

Due to type erasure, both parameter types ultimately become List, resulting in a method signature conflict.

3. What Are Reified Generics?

Reified generics refer to the ability to still retain and use the type information of generic parameters at runtime.

For example, C# generics retain concrete type parameter information at runtime.

List<string> names = new List<string>();
List<int> numbers = new List<int>();

At runtime, different constructed types can be distinguished.

The runtime implementation of C# generics differs from Java type erasure; it can leverage concrete type information to support runtime type checking, reflection, and runtime processing tailored to different types.

It should be noted that reified generics do not mean that all generic languages adopt exactly the same implementation approach.

4. Comparison of Generic Implementations Across Languages

Language Characteristics of Generic Implementation Runtime Type Information
Java Type erasure Most generic parameter information is not retained as ordinary runtime types
C# Reified generics Retains constructed generic type information
C++ Template instantiation Generates corresponding instances based on template arguments
Rust Mainly generic monomorphization Concrete type implementations generated at compile time
Go Implementation strategies such as GC Shape Should not be simply classified as traditional type erasure or full reification
TypeScript Compile-time type system Type declarations are usually erased when generating JavaScript

These implementation approaches reflect the design trade-offs different languages make among compilation efficiency, runtime overhead, code size, and compatibility.

8. Generics, Covariance, and Contravariance

The compatibility relationships between generic types are not always consistent with the inheritance relationships of their inner types.

This involves type variance.

This mainly includes:

  • Covariance.
  • Contravariance.
  • Invariance.

1. Covariance

If Dog is a subtype of Animal, then under the covariance rule:

Container<Dog> can be treated as Container<Animal>.

For example:

interface Animal {
    name: string;
}

interface Dog extends Animal {
    bark(): void;
}

interface Producer<T> {
    get(): T;
}

If Producer<T> is covariant with respect to T, then:

Producer<Dog> can be assigned to Producer<Animal>.

The reason is that a producer only provides data outward.

Any Dog can be used as an Animal.

2. Contravariance

Contravariance goes in the opposite direction from covariance.

If Dog is a subtype of Animal, then:

Consumer<Animal> can be used in scenarios that require Consumer<Dog>.

For example:

interface Consumer<T> {
    accept(value: T): void;
}

A consumer that can handle all Animals can naturally also handle Dogs.

But a consumer that can only handle Dogs cannot necessarily handle any Animal.

3. Invariance

Invariance means that generic types do not automatically become compatible with one another just because their inner types have an inheritance relationship.

For example, mutable containers usually require careful handling of covariance issues.

Suppose:

Dog is a subtype of Animal

If it were allowed to:

assign List<Dog> to List<Animal>

then the receiving side could add a Cat to this list.

A list that was originally only allowed to store Dogs would then be broken.