Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 2 of 7
Function Types, Callbacks & Higher-Order Functions
Functions are first-class values in TypeScript. Function types describe what arguments a function takes and what it returns - essential for callbacks, event handlers, middleware, and higher-order functions. TypeScript checks callback compatibility structurally.
Function Types & Callbacks
// ── Function type syntax ──────────────────────────────────────
type Predicate<T> = (item: T) => boolean;
type Transformer<T, U> = (input: T) => U;
type AsyncOperation<T> = (input: T) => Promise<T>;
// ── Typed callbacks ────────────────────────────────────────────
function filterTasks(
tasks: Task[],
predicate: Predicate<Task>,
): Task[] {
return tasks.filter(predicate);
}
const urgentTasks = filterTasks(tasks, (t) => t.priority === "critical");
// ── Higher-order function - returns a typed function ──────────
function createStatusFilter(status: TaskStatus): Predicate<Task> {
return (task) => task.status === status;
}
const isDone = createStatusFilter("done");
const isActive = createStatusFilter("in-progress");
const doneTasks = tasks.filter(isDone);
// ── Function interface (call signature) ───────────────────────
interface Formatter {
(value: unknown): string; // call signature
version: string; // additional property
}
const jsonFormat: Formatter = Object.assign(
(value: unknown) => JSON.stringify(value, null, 2),
{ version: "1.0" }
);
// ── Method vs function type in interfaces ─────────────────────
interface TaskService {
// Method shorthand - bivariant (looser)
findById(id: number): Task | undefined;
// Function property - contravariant (stricter, recommended)
findByTitle: (title: string) => Task | undefined;
}
// ── typeof for getting function types ─────────────────────────
function createTask(title: string, priority: Priority): Task {
return { /* ... */ } as Task;
}
type CreateTaskFn = typeof createTask;
// CreateTaskFn = (title: string, priority: Priority) => Task
// Reuse the type without re-specifying it
// ── Partial application via wrapping ─────────────────────────
function withLogging<T extends unknown[], R>(
fn: (...args: T) => R
): (...args: T) => R {
return (...args) => {
console.log("Calling with", args);
const result = fn(...args);
console.log("Result:", result);
return result;
};
}
const loggedCreate = withLogging(createTask);
loggedCreate("My Task", "high"); // ✅ fully typedCommon Mistakes
- Typing callbacks as `Function` - `Function` is as unsafe as `any` for functions. Always use a specific signature: `(e: Event) => void`.
- Expecting callback arity to be enforced - TypeScript allows callbacks with fewer parameters than declared (structural compatibility). `arr.forEach((item) => ...)` is valid even though forEach provides 3 args.
- Confusing method shorthand with function property - method shorthands (`fn()`) are bivariant; function properties (`fn:`) are strictly checked. For maximum safety, use function property syntax in interfaces.
Tip
Tip
Practice Function Types Callbacks HigherOrder Functions in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Function Types, Callbacks & Higher-Order Functions
Practice Task
Note
Practice Task - (1) Write a working example of Function Types Callbacks HigherOrder Functions from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Function Types Callbacks HigherOrder Functions is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Functions are first-class values in TypeScript.
- Typing callbacks as `Function` - `Function` is as unsafe as `any` for functions. Always use a specific signature: `(e: Event) => void`.
- Expecting callback arity to be enforced - TypeScript allows callbacks with fewer parameters than declared (structural compatibility). `arr.forEach((item) => ...)` is valid even though forEach provides 3 args.
- Confusing method shorthand with function property - method shorthands (`fn()`) are bivariant; function properties (`fn:`) are strictly checked. For maximum safety, use function property syntax in interfaces.
Finished this lesson?