Function Types
Functions and Types•Section 1 of 2•intermediate
Topic Overview
Take your time to understand each concept. Practice with the examples below!
Functions in TypeScript are supercharged! You can define exactly what goes in and what comes out, making them safer and easier to use. Let's explore how TypeScript makes functions better.
What are Function Types?
Just like variables have types, functions have types too! A function type describes:
- •What parameters it accepts (and their types)
- •What it returns (the return type)
- •Whether parameters are optional
Function Type Syntax:
- •Basic:(param: type) => returnType
- •Multiple params:(x: number, y: number) => number
- •Optional params:(name: string, age?: number) => void
- •Rest params:(...args: string[]) => void
Type Aliases for Functions:
Instead of repeating function types, give them names:
- •type MathOperation = (a:number, b: number) => number
- •type EventHandler = (event:MouseEvent) => void
- •type Formatter = (value:any) => string
Functions as First-Class Citizens:
In TypeScript, functions can be:
- •Stored in variables
- •Passed as arguments to other functions
- •Returned from functions
- •Stored in arrays or objects
Higher-Order Functions:
Functions that work with other functions:
- •Accept functions as parameters
- •Return functions as results
- •Transform or combine functions
- •Common in functional programming
Real-World Use Cases:
- •Event handlers:onClick, onChange functions
- •Array methods:map, filter, reduce callbacks
- •API callbacks:Success and error handlers
- •Utility functions:Formatters, validators
Benefits of Typed Functions:
- •Clear contracts:Know what a function expects and returns
- •Better IntelliSense:Auto-complete for parameters
- •Fewer runtime errors:Catch mistakes at compile time
- •Self-documenting:Types explain how to use the function
Example
// Function type definitionstype MathOperation = (x: number, y: number) => number;type StringFormatter = (input: string) => string;// Function implementationsconst add: MathOperation = (x, y) => x + y;const multiply: MathOperation = (x, y) => x * y;const uppercase: StringFormatter = (input) => input.toUpperCase();const removeSpaces: StringFormatter = (input) => input.replace(/\s/g, '');// Higher-order functionsfunction calculate(operation: MathOperation, x: number, y: number): number { return operation(x, y);}function processString(formatter: StringFormatter, text: string): string { return formatter(text);}// Function as parameters and return valuesfunction createMultiplier(factor: number): (x: number) => number { return (x: number) => x * factor;}// Using the functionsconsole.log(calculate(add, 5, 3));console.log(calculate(multiply, 4, 7));console.log(processString(uppercase, "hello world"));const double = createMultiplier(2);console.log(double(10));