Functions as Values
What you'll learn: How to type variables that hold functions and pass functions around like any other value.
In JavaScript, functions are first-class citizens — you can assign them to variables, pass them to other functions, and return them from functions. TypeScript lets you explicitly type these function values to ensure type safety.
Typing Function Variables
When you store a function in a variable, you can annotate that variable with a function type:
// Declaring a variable that holds a function
let greet: (name: string) => string;
greet = function(name: string) {
return `Hello, ${name}`;
};
// Or with an arrow function
greet = (name: string) => `Hello, ${name}`;
The type (name: string) => string describes a function that takes a string parameter and returns a string.
Passing Functions as Arguments
You can type parameters that expect function values:
function runTwice(fn: (x: number) => number, value: number): number {
return fn(fn(value));
}
const double = (x: number) => x * 2;
runTwice(double, 5); // Returns 20
Here, fn is typed as a function that takes a number and returns a number. TypeScript ensures you only pass compatible functions.
Think of It Like This
Imagine a toolbox where each tool (function) has a label describing what it accepts and produces. You can hand tools to other workers (functions), and TypeScript checks that you're passing the right tool for the job.
Key Takeaway: Functions are values in TypeScript, and you type them using the syntax (params) => returnType to ensure they're used correctly when stored in variables or passed as arguments.