October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How to Pass Functions as Parameters in TypeScript

Pass a function to TypeScript code by describing its callback arguments and return type. Learn when to use inline signatures, aliases, generics, and this annotations.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Type a function parameter with the callback’s input and return types: (argument: ArgumentType) => ReturnType. For example, (name: string) => void describes a callback that accepts a string and whose return value the caller does not use.

Write a function type for the callback

A function type expression has the same shape as an arrow function’s parameter and return-type portion. Put it directly in the receiving function’s parameter list when the callback is used once:

As an Amazon Associate I earn from qualifying purchases.

function greetWith(greet: (name: string) => void) {
  greet("Ada");
}

Here, greet must be a function that accepts a string. The void return type means greetWith does not use the callback’s returned value; it does not mean the callback must have no return expression. TypeScript can infer the parameter type when you provide an inline callback:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
greetWith(name => {
  console.log(`Hello, ${name}`);
});

Because the callback parameter is contextually typed, you do not need to annotate name again. Function type parameters need names syntactically, but those names are descriptive and do not have to match the implementation’s parameter names.

Give a reused callback shape a name

If multiple functions accept the same kind of callback, define a type alias instead of repeating the signature:

type Predicate = (value: string) => boolean;

function filterNames(names: string[], test: Predicate): string[] {
  return names.filter(test);
}

Predicate says the callback receives a string and returns a boolean. The alias makes the parameter’s purpose easier to recognize and lets the same signature be reused consistently. For a single, self-explanatory callback, an inline type is often clearer.

Make callback parameters match how the function is called

Do not mark a supplied argument optional

An optional parameter in a callback type says the function receiving that callback may call it without providing that argument. It does not merely say that a callback implementation is allowed to ignore the argument.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
// The receiver always supplies a string:
type NameHandler = (name: string) => void;

function visitName(handler: NameHandler) {
  handler("Ada");
}

Use name?: string only if the receiving function may actually invoke the callback without a name. The TypeScript Handbook puts it this way: “When writing a function type for a callback, never write an optional parameter unless you intend to call the function without passing that argument”. TypeScript Handbook: More on Functions.

A callback can ignore arguments it does not need

A function that supplies several callback arguments does not require every callback to declare all of them. For example, an array’s forEach callback can use only the current item even though the API can also supply its index and the array:

["Ada", "Grace"].forEach(name => {
  console.log(name);
});

This is different from making later callback parameters optional. The callback may accept fewer parameters; mark a parameter optional only when the caller may omit it. See the Handbook’s function compatibility guidance.

Use generics when types must stay connected

A generic is useful when a type needs to flow through multiple positions—for example, when a callback transforms an input of type Input into an output of type Output:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function mapOne<Input, Output>(
  value: Input,
  transform: (item: Input) => Output
): Output {
  return transform(value);
}

const length = mapOne("TypeScript", text => text.length);

TypeScript infers Input as string and Output as number in this call, so length is a number. The generic signature preserves the relationship between the value passed in, the callback’s input, and the returned result.

Do not add a generic merely because one parameter is a function. If the callback’s types do not need to relate to another parameter or the result, a direct signature is usually simpler. The Handbook covers generic inference and generic functions and cautions against type parameters that do not improve the relationship or inference.

Account for this when an API controls the call

Some libraries invoke callbacks without the object receiver a callback might otherwise expect. If a callback must not rely on a this value, express that in its type with a this: void parameter:

type ClickHandler = (this: void, event: Event) => void;

The this parameter is a TypeScript-only annotation; it is not a normal argument passed at runtime. A callback that uses this may fail when supplied to an API that calls it without a receiver. Check the library’s callback contract before depending on a method’s this. The Handbook’s Functions documentation explains callback this annotations.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Reuse an existing function’s parameter types

When a callback should match the parameters of an existing function, the Parameters<Type> utility extracts those parameter types as a tuple:

function formatName(first: string, last: string) {
  return `${first} ${last}`;
}

type FormatNameArgs = Parameters<typeof formatName>;
// [first: string, last: string]

This can help avoid duplicating a parameter list when building related types. For an overloaded function, Parameters<Type> uses the final signature. See TypeScript’s Utility Types reference.

Prefer precise types to any

Using any for a callback’s arguments or result removes the checks that make the function signature useful. State the actual input and output types; use a generic only when it captures a real relationship. TypeScript’s Do’s and Don’ts guidance advises against any except as a migration aid for JavaScript and against generic parameters that do not contribute to the type.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.