Type Systems

How languages classify values and catch mismatches: static vs dynamic, strong vs weak, inference, nominal vs structural.

What is it?

Every value has a type: a number, a string, a list, a User. A type system is the set of rules a language uses to decide which operations are allowed on which types, and when it checks those rules.

Four separate questions describe most type systems:

- When are types checked? Static languages (Java, Rust, TypeScript, C) check before the program runs. Dynamic languages (Python, JavaScript, Ruby) check while it runs. - How strict are conversions? Strong typing refuses to silently mix unrelated types ("1" + 1 is an error in Python). Weak typing converts quietly ("1" + 1 is "11" in JavaScript). - Do you have to write the types? With type inference the compiler works them out (let x = 5 is an integer in Rust and TypeScript). - What makes two types compatible? Nominal systems compare names (Java). Structural systems compare shapes (TypeScript, Go interfaces).

Gradual typing mixes both worlds: you add type annotations where they help, and leave the rest dynamic (TypeScript over JavaScript, type hints plus mypy over Python).

Explain like I'm 10

A static type system is a building inspector who checks the plans before construction starts. A dynamic one is an inspector who walks through the finished building and stops you at the broken stair. Strong vs weak is whether the inspector refuses a square peg in a round hole, or quietly shaves the peg down to fit.

Examples

Dynamic and strong (Python) vs dynamic and weak (JavaScript)

# Python: types are checked at run time, and mixing is refused
count = 3
label = "items: " + str(count)   # fine, explicit conversion
label = "items: " + count        # TypeError at run time

# JavaScript, for comparison (weak):
#   "items: " + 3   -> "items: 3"
#   "5" * 2         -> 10
#   [] + {}         -> "[object Object]"

Static typing with inference and structural compatibility (TypeScript)

interface Point { x: number; y: number }

function length(p: Point): number {
  return Math.hypot(p.x, p.y);
}

const origin = { x: 0, y: 0, label: "O" }; // type inferred, no annotation
length(origin);           // OK: it has x and y, so it fits Point
length({ x: 1 });         // compile error: property 'y' is missing

let total = 10;           // inferred as number
total = "ten";            // compile error before the code ever runs

TypeScript never required origin to declare that it is a Point. It only checked that the shape matches. In Java, a class must explicitly implements Point to be accepted.

How it works

A static checker (compiler or type checker) reads the source, assigns a type to every expression and verifies each operation against the rules. If something doesn't fit, you get an error before the program runs. Many compilers then erase the types (TypeScript emits plain JavaScript) or use them to generate faster code (Rust, C).

A dynamic language attaches a type tag to every value at run time. Each operation inspects the tags first: Python's + checks whether both operands support addition with each other, and raises TypeError if not.

Type inference works by propagating known facts: 5 is a number, so let x = 5 makes x a number, so x + 1 is a number. Languages like Rust and Haskell can infer almost everything inside a function, though function signatures are usually written out.

Nominal vs structural is about compatibility. Nominal: a Celsius and a Fahrenheit class are different even if both wrap one number. Structural: any object with the right fields and methods fits.

weak                       strong
            +---------------------+----------------------+
  static    | C                   | Java, Rust, Go,      |
            |                     | TypeScript*          |
            +---------------------+----------------------+
  dynamic   | JavaScript, PHP     | Python, Ruby         |
            +---------------------+----------------------+
  * TypeScript is static at compile time but runs as JavaScript.
  Strong/weak is a spectrum, not a clean yes/no.

Why does it exist?

Types catch a whole class of bugs (calling a method that doesn't exist, passing a string where a number is expected) and document what code expects. Static checks find those bugs earlier and enable editor features like autocomplete and safe renames. Dynamic typing trades those guarantees for less ceremony and faster experimentation. Gradual typing exists because many teams want both: quick scripts that can grow into checked code.

When to use it

Lean on static types for large codebases, long-lived code, shared libraries and anything many people change: the checker becomes a safety net during refactors. Dynamic typing shines for small scripts, notebooks, prototypes and glue code. In Python or JavaScript projects that keep growing, adopt gradual typing (type hints, TypeScript) at module boundaries first.

When not to use it

Don't fight the type system with escape hatches (any, casts, # type: ignore) everywhere; that keeps the cost and loses the benefit. Don't treat static types as proof of correctness either: they check shapes, not logic, and data from outside the program (JSON, user input) still needs run-time validation.

Common mistakes

  • Treating 'static vs dynamic' and 'strong vs weak' as the same thing. Python is dynamic but strong; C is static but fairly weak.

  • Assuming TypeScript or Python type hints check data at run time. They are erased or ignored when the program runs, so parsed JSON must still be validated.

  • Overusing any (TypeScript) or Any (Python), which silently switches checking off for everything that value touches.

  • Expecting nominal behaviour in a structural system: two TypeScript interfaces with the same fields are interchangeable even if their names suggest otherwise.

  • Believing inferred types are weaker than written ones. An inferred type is just as strictly checked; it is only not spelled out.

Practice exercises

  1. Easy:

    Predict the result of '3' + 4, '3' * 4 and 3 + True in both JavaScript and Python, then run them to check.

  2. Medium:

    Add type hints to a small untyped Python module (3–4 functions) and run mypy on it. Fix every error it reports and write down which ones were real bugs.

  3. Hard:

    In TypeScript, make UserId and OrderId (both strings at run time) incompatible with each other using a 'branded type', so passing one where the other is expected fails to compile.

Interview questions

What is the difference between static and dynamic typing?

Static typing checks types before the program runs (at compile or check time), so type errors stop the build. Dynamic typing checks types while the program runs, so a type error surfaces only when the faulty line executes.

What is the difference between strong and weak typing?

It describes how willingly a language converts between unrelated types. Strong typing refuses implicit conversions that could lose meaning (Python raises on '1' + 1). Weak typing converts silently (JavaScript gives '11'). It is a spectrum, not a strict binary.

Is Python statically or dynamically typed? Strongly or weakly?

Dynamically and strongly typed. Variables have no fixed type, but values do, and Python refuses most implicit conversions between unrelated types.

What is type inference?

The compiler deducing types from how values are created and used, so you don't have to annotate them. let x = 5 in Rust or TypeScript gives x a numeric type that is checked just as strictly as if you had written it.

What is the difference between nominal and structural typing?

Nominal typing considers types compatible only if they are declared related by name (Java classes must implements an interface). Structural typing considers them compatible if their shape matches: same fields and methods (TypeScript, Go interfaces).

What is duck typing and how does it relate to structural typing?

Duck typing is structural compatibility checked at run time: if an object has the method you call, it works, whatever its class. Structural typing applies the same idea at compile time.

What is gradual typing?

A system where typed and untyped code coexist, so you can add annotations incrementally. TypeScript's any and Python's type hints checked by mypy or pyright are examples. Unannotated parts are treated as dynamic.

Do TypeScript types exist at run time?

No. The compiler erases them, so the emitted JavaScript has no type information. Run-time checks need explicit code such as typeof, instanceof or a schema validator.

What are the main trade-offs of static typing?

Benefits: earlier bug detection, safer refactoring, better tooling and self-documenting code. Costs: more upfront ceremony, a learning curve for advanced types, and occasionally fighting the checker over code you know is correct.

What is a 'sound' type system?

One where a program that type-checks can never hit a type error at run time. Few mainstream languages are fully sound; TypeScript deliberately is not, trading soundness for compatibility with existing JavaScript patterns.