Course contentsShow
← Computer Science
Lesson 1990 of 2,87245. Type Systems and SemanticsFree lesson

Type Checking

Understanding how type checkers verify that operations are applied to values of appropriate types before or during execution.

Type Checking

You'll learn how compilers verify that operations match the types of their operands before runtime errors occur.

What is Type Checking?

Type checking is the process a compiler or interpreter uses to verify that every operation in your program is applied to values of the correct types. Think of it like a grammar checker for your code's logic—it ensures you're not trying to add a string to a function, or call a number like it's a function.

The type checker walks through your program (often the AST you built in earlier phases) and assigns types to expressions, then validates that each operation is type-safe. For example, if you write x + y, the type checker confirms that both x and y have types that support addition (like both being integers, or both being floats).

When Type Checking Happens

Type checking can occur:

  • Statically (before execution): The compiler checks types during compilation. Most statically-typed languages like Java, C++, or Haskell do this.
  • Dynamically (during execution): The interpreter checks types as operations execute. Python and JavaScript work this way.

The Checking Process

The type checker uses type rules that define what's legal. For instance:

  • "If e1 has type int and e2 has type int, then e1 + e2 has type int"
  • "A function call is valid only if the argument types match the parameter types"

When a type mismatch is detected, the checker reports an error, preventing type-unsafe code from running.

Connection to Type Soundness

Type checking is how we enforce type soundness (which you learned about earlier). A sound type system guarantees that well-typed programs won't have certain runtime errors—and type checking is the mechanism that ensures your program is well-typed.

Key Takeaway: Type checking verifies that operations are applied to appropriately-typed values, catching type errors before or during execution to ensure type safety.