Functions in TypeScript · Lesson 7 of 17
Typing Functions in TypeScript
Functions are where types pay off most: a typed signature tells every caller exactly what to pass and what comes back, and TypeScript checks every call. This lesson covers typing parameters and returns, optional and default values, and function types for callbacks – the patterns you'll use in every React component and Node handler.
In this lesson
- Parameter and return types
- Optional, default and rest parameters
- Destructured options objects
- Function types and callbacks
Parameters and return types
function addGst(amount: number, rate: number): number {
return Math.round(amount * (1 + rate) * 100) / 100;
}
const formatInr = (amount: number): string => `Rs ${amount.toLocaleString("en-IN")}`;
function logTotal(label: string, amount: number): void {
console.log(`${label}: ${formatInr(amount)}`);
}
logTotal("Laptop", addGst(54999, 0.18));
logTotal("Book", addGst(450, 0.05));
Laptop: Rs 64,898.82 Book: Rs 472.5
Return types can usually be inferred, but writing them on exported functions documents the contract and catches mistakes inside the function – like a branch that forgets to return.
Optional, default and rest parameters
function greet(name: string, title?: string): string { // optional: string | undefined
return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}
function paginate(total: number, pageSize = 10, page = 1): string { // defaults infer their types
const pages = Math.ceil(total / pageSize);
return `page ${page} of ${pages}`;
}
function sum(...values: number[]): number { // rest: any number of arguments
return values.reduce((a, b) => a + b, 0);
}
console.log(greet("Asha"), "|", greet("Verma", "Dr."));
console.log(paginate(95), "|", paginate(95, 20, 3));
console.log(sum(), sum(5), sum(1, 2, 3, 4));
Hello, Asha | Hello, Dr. Verma page 1 of 10 | page 3 of 5 0 5 10
Options objects
When a function has many settings, take one typed object instead of a long list of positional parameters:
interface FetchOptions {
url: string;
method?: "GET" | "POST" | "PUT" | "DELETE";
retries?: number;
timeoutMs?: number;
}
function describeRequest({ url, method = "GET", retries = 0, timeoutMs = 5000 }: FetchOptions): string {
return `${method} ${url} (retries ${retries}, timeout ${timeoutMs} ms)`;
}
console.log(describeRequest({ url: "/api/courses" }));
console.log(describeRequest({ url: "/api/orders", method: "POST", retries: 2 }));
GET /api/courses (retries 0, timeout 5000 ms) POST /api/orders (retries 2, timeout 5000 ms)
Callers name each option, can skip any optional ones, and TypeScript rejects misspelt names like retrys. This is exactly how React props work.
Function types and callbacks
type Predicate<T> = (item: T) => boolean;
type Comparator = (a: number, b: number) => number;
function filterItems<T>(items: readonly T[], keep: Predicate<T>): T[] {
const result: T[] = [];
for (const item of items) if (keep(item)) result.push(item);
return result;
}
const descending: Comparator = (a, b) => b - a; // a and b inferred as number
const marks = [72, 95, 41, 88];
console.log(filterItems(marks, (m) => m >= 50));
console.log(filterItems(["ts", "cpp", "go"], (s) => s.length > 2));
console.log(marks.toSorted(descending));
function onEvent(handler: (eventName: string, at: Date) => void): void {
handler("click", new Date("2026-11-07T10:00:00Z"));
}
onEvent((name, at) => console.log(`${name} at ${at.toISOString()}`));
[ 72, 95, 88 ] [ 'cpp' ] [ 95, 88, 72, 41 ] click at 2026-11-07T10:00:00.000Z
Contextual typing
When you pass an arrow function where TypeScript already knows the expected function type, its parameters are typed automatically – that's why (m) => m >= 50 needs no annotation. You almost never annotate callback parameters in array methods or event handlers.
Common errors caught at call sites
function bookSeat(seat: number, passenger: string, meal?: "veg" | "non-veg"): string {
return `${passenger} → seat ${seat}${meal ? ` (${meal})` : ""}`;
}
bookSeat("12A", "Asha");
bookSeat(12);
bookSeat(14, "Ravi", "vegan");
console.log(bookSeat(12, "Meera", "veg"));
main.ts(4,10): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. main.ts(5,1): error TS2554: Expected 2-3 arguments, but got 1. main.ts(6,22): error TS2345: Argument of type '"vegan"' is not assignable to parameter of type '"non-veg" | "veg" | undefined'.
Practice
Try it yourself
Write
applyDiscount(price: number, percent = 10, cap?: number): numberwhere cap limits the maximum discount.Show solution
function applyDiscount(price: number, percent = 10, cap?: number): number { let discount = (price * percent) / 100; if (cap !== undefined) discount = Math.min(discount, cap); return price - discount; } console.log(applyDiscount(1000), applyDiscount(1000, 25), applyDiscount(5000, 30, 500));900 750 4500
Quick check
What is the type of an optional parameter title?: string?
string | undefined.
How do you type a callback that takes a number and returns a boolean?
(value: number) => boolean.
Why use an options object?
Named, optional settings that are easy to extend and checked for typos.
Summary
- Always type parameters; type return values of exported functions.
- Use ?, defaults and ...rest for flexible signatures; options objects for many settings.
- Function types describe callbacks; contextual typing fills in callback parameters.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.