Type Annotations and Signatures
You'll learn how programmers explicitly tell the compiler or type checker what types their code expects and returns.
The Core Idea
When you write code, the type system needs to know what types your variables, function parameters, and return values have. Type annotations are the syntax you use to explicitly declare these types in your source code. A function signature is the complete declaration showing its parameter types and return type—think of it as a contract that promises what the function accepts and produces.
Instead of letting the compiler infer types (or risking mistakes in dynamically-typed languages), annotations make types explicit and checkable.
Why Annotate?
Without annotations, you might write:
function add(x, y)
return x + y
What types are x and y? Integers? Floats? Strings? The type checker can't be sure.
With annotations:
function add(x: int, y: int) -> int
return x + y
Now it's crystal clear: both parameters must be int, and the result is int. The type checker can verify every call to add respects this contract.
Annotations in Practice
- Variables:
let count: int = 0 - Parameters:
function greet(name: string) - Return types:
function compute() -> float - Complete signatures:
function map(f: int -> int, list: [int]) -> [int]
These annotations enable type checking before runtime, catching mismatches early. They also serve as documentation, making code easier to understand and maintain.
Key Takeaway: Type annotations and signatures are explicit declarations that tell the type system what types variables and functions expect, enabling early error detection and clearer code contracts.