Typed Functions
TypeScript functions have typed parameters, return types, optional/default parameters, rest parameters, and function overloads. Proper function typing is the backbone of safe, predictable codebases.
35 min•By Priygop Team•Last updated: Feb 2026
Function Typing Patterns
Example
// Basic function types
function add(a: number, b: number): number {
return a + b;
}
// Arrow function with types
const multiply = (a: number, b: number): number => a * b;
// Function type alias
type MathOperation = (a: number, b: number) => number;
const subtract: MathOperation = (a, b) => a - b;
// Optional and default parameters
function createUser(
name: string,
role: string = "viewer",
age?: number
): { name: string; role: string; age?: number } {
return { name, role, ...(age !== undefined && { age }) };
}
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((acc, n) => acc + n, 0);
}
// Function overloads
function formatDate(date: Date): string;
function formatDate(date: string): Date;
function formatDate(date: Date | string): string | Date {
if (date instanceof Date) {
return date.toISOString().split("T")[0];
}
return new Date(date);
}
const str = formatDate(new Date()); // TypeScript knows: string
const dateObj = formatDate("2025-01-01"); // TypeScript knows: Date
// Callback typing
function fetchData(
url: string,
onSuccess: (data: unknown) => void,
onError?: (error: Error) => void
): void {
// Implementation...
}
// this parameter (explicit this type)
interface Button {
label: string;
onClick(this: Button): void;
}