Functions
Introduction to Functions
Functions are the building blocks of any program. They let you package up logic
into reusable pieces with clear inputs and outputs.
function add(a: number, b: number): number {
return a + b
}
Think of functions as transformations: data goes in, data comes out.
Functions that always produce the same output for the same input (and don't
change anything outside themselves) are called pure functions. They're the
foundation of reliable, testable code.
Anatomy of a TypeScript Function
function greet(name: string): string {
// โ parameter โ return type
return `Hello, ${name}!`
}
- Parameters have types that specify what the function accepts
- Return type specifies what the function produces
- TypeScript enforces both at compile time
Why Type Functions?
Types create a contract. Anyone calling your function knows:
- What arguments to provide
- What they'll get back
// Without types - what does this accept? Return?
function process(data) {
// ๐คท
}
// With types - crystal clear!
function process(data: Array<string>): number {
return data.length
}
Type Inference
TypeScript is smart! It can often infer the return type:
function double(n: number) {
return n * 2 // TypeScript knows this returns number
}
But explicit return types are helpful for:
- Documentation
- Catching mistakes early
- Complex functions
Function Forms
TypeScript supports multiple ways to write functions:
// Function declaration - best for top-level named functions
function processOrder(order: Order): Receipt {
// ...
}
// Arrow function - best for callbacks and short functions
const double = (n: number): number => n * 2
// Arrow function with implicit return
const items = numbers.map((n) => n * 2)
In this exercise, you'll start with the basic function declaration syntax and
return values, then add parameters and TypeScript types and learn when to use
each function form.