Function Programs
Function Programs — purpose and prerequisites
Function exercises practice parameter types, return values, callbacks, and keeping operations small. A well-typed higher-order function can operate on values without knowing where they came from. Prefer a named result type when the output carries multiple related properties.
What you’ll learn
- Explain the purpose of function programs.
- Identify the typed contract, runtime responsibilities and common pitfalls.
- Run the example and extend its behavior with a practical exercise.
How the idea works
transform receives a callback and applies it to each array element. The same function handles squaring and incrementing without changing the original array.
A callback typed (n: number) => number cannot safely return undefined where number is required.
Visualize the flow
Run the checked TypeScript example
This source was compiled using TypeScript 5.8.3 with strict checking, then executed with Node.js 22.16.0. Its stdout below is the actual captured output. The core logic is runnable without a framework or a remote API; integration-specific examples appear in a separate lab when needed.
TypeScript source
function transform(values: readonly number[], operation: (n: number) => number): number[] {
return values.map(operation);
}
const original = [2, 4, 6];
console.log(transform(original, n => n * n));
console.log(transform(original, n => n + 1));Verified output
[ 4, 16, 36 ]
[ 3, 5, 7 ]Compile: npx tsc --strict --target es2022 --module commonjs function-programs.ts; run: node function-programs.js. For examples importing node: modules, install @types/node as a development dependency; for browser or React projects use the separate lab setup.
Trace the execution
transform receives a callback and applies it to each array element. The same function handles squaring and incrementing without changing the original array.
Before editing the code, predict what the output will be for one changed input. Run it and compare your prediction with the actual result.
Common mistake and correction
A callback typed (n: number) => number cannot safely return undefined where number is required.
Determine whether the issue belongs to the type system, a trust boundary, or actual runtime behavior before choosing a correction.
Your turn: extend the example
Write a reusable filterValues function accepting a typed predicate callback.
Record expected success and failure outcomes, run the code, and compare the observed behavior. Keep the exercise compatible with strict type checking.
Check your understanding
Key idea to remember
transform receives a callback and applies it to each array element. The same function handles squaring and incrementing without changing the original array.
Apply the same reasoning to the practice task, then integrate it into a real app only when the runtime and dependency setup are ready.
Reaching the recap and completing the quizzes are separate milestones.