TypeScript example

How to type a callback function in TypeScript

8 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

Give the parameter a function type: onDone: (total: number) => void, or name it once with type OnDone = (total: number) => void;. TypeScript then checks every callback passed in, infers the types of an arrow function's parameters, and types what the callback returns. Don't use Function or any: both accept any function and check none of its arguments.

A callback is just a function passed as an argument, so its type is a function type: the parameter list, an arrow, and the return type. Write it inline in the parameter list or as a reusable type alias, and the checker does three jobs at once: it rejects callbacks with the wrong signature, it gives the parameters of an inline arrow their types without annotations, and it knows the type of the callback's result. The sections below cover function types, the error a wrong callback gives, why Function is not the answer, call signatures in interfaces, generic callbacks, and optional, error-first and async callbacks. Each example runs on this page: hit Run, then edit the code and run it again.

1A function type: (args) => return typeRecommended

The syntax mirrors an arrow function: (done: number, total: number) => void. The parameter names are only documentation, and both the names and the types are required in the type: a bare (number) => void declares a parameter named number of type any, which strict mode reports as error TS7051: Parameter has a name but no type. Did you mean 'arg0: number'? Put the type straight into the parameter list, or give it a name with type when more than one function uses it. A void return type says the caller ignores whatever the callback returns.

function-type.ts
// A function type: parameter names and types, then => and the return type
type OnProgress = (done: number, total: number) => void;

// Use the alias, or write the type inline in the parameter list
function processAll(
    files: string[],
    onProgress: OnProgress,
    format: (name: string) => string,
): void {
    files.forEach((file, i) => {
        console.log(format(file));
        onProgress(i + 1, files.length);
    });
}

// The arrows need no annotations: done, total and name are inferred
// from the parameter types above (contextual typing)
processAll(
    ["a.txt", "b.txt"],
    (done, total) => console.log(`  ${done}/${total}`),
    (name) => name.toUpperCase(),
);

// A named function works too, as long as its signature fits
function logPercent(done: number, total: number): void {
    console.log(`${Math.round((done / total) * 100)}%`);
}
processAll(["c.txt"], logPercent, (name) => `file ${name}`);

Output

Prints A.TXT, 1/2, B.TXT, 2/2, then file c.txt and 100%. The arrows passed to processAll have no annotations at all, yet name.toUpperCase() type-checks: TypeScript reads name's type off the parameter it is passed to. That is why annotating the callback parameter once beats annotating every arrow. The named function logPercent is accepted because its signature matches OnProgress, not because of its name. Leave the callback parameter without a type and this page's compiler quietly makes it any; with strict on, as in most projects, it is error TS7006: Parameter 'onProgress' implicitly has an 'any' type.

2What the checker catches

Typing the callback moves mistakes from runtime to compile time. Below, logStatus expects a string, but processAll calls its callback with numbers. In plain JavaScript this would throw inside the loop, on the first call; here the type error stops the run before anything executes. This embed fails on purpose.

wrong-callback.ts
type OnProgress = (done: number, total: number) => void;

function processAll(files: string[], onProgress: OnProgress): void {
    files.forEach((_, i) => onProgress(i + 1, files.length));
}

// This callback expects a string, but processAll passes numbers
function logStatus(status: string): void {
    console.log(status.toUpperCase());
}

processAll(["a.txt", "b.txt"], logStatus);

Output

The compiler reports error TS2345: Argument of type '(status: string) => void' is not assignable to parameter of type 'OnProgress'. followed by Types of parameters 'status' and 'done' are incompatible. and Type 'number' is not assignable to type 'string'. Notice what it did not complain about: logStatus takes one parameter where OnProgress passes two. A callback may ignore trailing arguments, just as [1, 2].map((n) => n * 2) ignores the index. The opposite is an error: a callback that needs a third parameter gives Target signature provides too few arguments. Expected 3 or more, but got 2.

3Why not Function or any

The most-voted question on this topic asks for a callback type that is not "universal any", and the built-in Function type is barely better. It accepts anything callable, including classes and functions of any arity, lets you call it with any arguments, and the call returns any. Compare it with a real function type on the same callback.

function-vs-any.ts
// The loose way: Function accepts anything callable and checks nothing
function runLoose(cb: Function): void {
    console.log(cb("not a number"));   // compiles: Function takes any arguments
}

// The typed way: the signature says what goes in and what comes out
function runTyped(cb: (n: number) => number): void {
    const result = cb(21);              // result is number, not any
    console.log(result.toFixed(1));
}

const double = (n: number): number => n * 2;

runLoose(double);   // runs, but double gets a string
runTyped(double);

// Function also accepts classes and functions of any shape
runLoose(JSON.stringify);
runLoose(() => "no parameters at all");

Output

runLoose(double) compiles and prints NaN: double was handed a string and nothing noticed. The typed version prints 42.0, and result.toFixed(1) is checked because result is a number. The last two lines show Function also taking JSON.stringify ("not a number") and a function with no parameters. When you really mean "any function", write (...args: never[]) => unknown or a generic instead; typescript-eslint's no-unsafe-function-type rule flags Function for this reason.

4Call signatures and callbacks in interfaces

An interface can describe a function too, with a call signature: (value: string): boolean;, written with a colon instead of an arrow. Use it when the function also carries properties, or when you prefer interface; for a plain callback it means the same as the arrow type. Callbacks that are members of an options object can use either method syntax, onChange(value: string): void, or property syntax, onError: (value: string, rule: string) => void.

call-signature.ts
// A call signature inside an object type: a function that also has properties
interface Validator {
    (value: string): boolean;   // no arrow: a call signature uses a colon
    label: string;
}

function makeMinLength(min: number): Validator {
    const check = (value: string): boolean => value.length >= min;
    return Object.assign(check, { label: `at least ${min} characters` });
}

// Callbacks as members of an options object
interface FieldOptions {
    validate: Validator;
    onChange(value: string): void;              // method syntax
    onError: (value: string, rule: string) => void;   // property syntax
}

function setValue(value: string, options: FieldOptions): void {
    if (options.validate(value)) {
        options.onChange(value);
    } else {
        options.onError(value, options.validate.label);
    }
}

const options: FieldOptions = {
    validate: makeMinLength(4),
    onChange(value) {
        console.log(`saved "${value}"`);
    },
    onError: (value, rule) => console.log(`"${value}" rejected: ${rule}`),
};

setValue("Ada Lovelace", options);
setValue("Ada", options);

Output

Prints saved "Ada Lovelace" and "Ada" rejected: at least 4 characters. The two member syntaxes differ in one way. With strict on (its strictFunctionTypes part), as in most projects, a callback that accepts less than the type promises is rejected for a property-syntax member: error TS2322: Type '(value: string) => void' is not assignable to type '(value: string | number) => void'. A method-syntax member skips that check even in strict mode, and this page's compiler runs without strict, so here both forms compile, and calling such a callback with 42 fails at runtime with TypeError: value.toUpperCase is not a function. Prefer property syntax for callbacks.

5Generic callbacks

When the callback works on whatever the caller passes in, make the function generic and use the type parameters in the callback's type. T ties the callback's input to the array, and U ties the result array to what the callback returns. This is how Array.prototype.map is typed, and callers never write the type arguments: TypeScript infers them.

generic-callback.ts
// T and U link the callback to the rest of the signature
function mapItems<T, U>(items: T[], fn: (item: T, index: number) => U): U[] {
    const out: U[] = [];
    for (let i = 0; i < items.length; i++) {
        out.push(fn(items[i], i));
    }
    return out;
}

// T is inferred from the array, U from what the callback returns
const lengths = mapItems(["red", "green", "blue"], (s) => s.length);
console.log(lengths);   // number[]

const labels = mapItems([3, 1, 2], (n, i) => `${i}:${n * 10}`);
console.log(labels);    // string[]

// A reusable generic callback type
type Predicate<T> = (item: T) => boolean;

function countWhere<T>(items: T[], test: Predicate<T>): number {
    return items.filter(test).length;
}

const isEven: Predicate<number> = (n) => n % 2 === 0;
console.log(countWhere([1, 2, 3, 4, 6], isEven));
console.log(countWhere(["a", "bb", "ccc"], (s) => s.length > 1));

Output

The two calls print [ 3, 5, 4 ] and [ '0:30', '1:10', '2:20' ]: the first callback returns a number, so lengths is number[], and the second returns a string, so labels is string[]. The first also shows a callback ignoring the index argument. A generic alias such as Predicate<T> is reused with any element type; the counts are 3 and 2.

6Optional, error-first and async callbacks

Mark an optional callback with ? and call it with onSaved?.(id), which does nothing when it is missing. Node-style callbacks take the error first: (err: Error | null, result?: T) => void. An async callback is one that returns a promise, so its type is () => Promise<string>, and the function that calls it awaits the result.

optional-async.ts
// An optional callback: check it, or call it with ?.()
function save(name: string, onSaved?: (id: number) => void): number {
    const id = name.length * 100;
    onSaved?.(id);
    return id;
}
save("report", (id) => console.log("saved as", id));
console.log("no callback:", save("notes"));

// A void return type accepts callbacks that return something:
// push returns the new length, and the result is simply ignored
const seen: string[] = [];
function each(items: string[], fn: (item: string) => void): void {
    for (const item of items) fn(item);
}
each(["x", "y"], (item) => seen.push(item));
console.log(seen);

// Node-style error-first callback
type Done<T> = (err: Error | null, result?: T) => void;

function parsePort(text: string, done: Done<number>): void {
    const port = Number(text);
    if (Number.isInteger(port) && port > 0 && port < 65536) {
        done(null, port);
    } else {
        done(new Error(`bad port: ${text}`));
    }
}
const report: Done<number> = (err, port) => {
    if (err !== null) console.log(err.message);
    else console.log("port", port);
};
parsePort("8080", report);
parsePort("80a", report);

// An async callback returns a Promise
async function retry(task: () => Promise<string>, times: number): Promise<string> {
    for (let attempt = 1; ; attempt++) {
        try {
            return await task();
        } catch (err) {
            console.log(`attempt ${attempt} failed`);
            if (attempt === times) throw err;
        }
    }
}

let calls = 0;
async function main() {
    const result = await retry(async () => {
        calls++;
        if (calls < 3) throw new Error("busy");
        return "done";
    }, 5);
    console.log(result, "after", calls, "calls");
}
main();

Output

saved as 600 comes from the callback, and no callback: 500 shows the call without one. Calling onSaved(id) without the ?. compiles here, but with strict on, as in most projects, it is error TS2722: Cannot invoke an object which is possibly 'undefined'. The [ 'x', 'y' ] line shows that a void callback type accepts an arrow that returns a value (push returns the new length). The error-first calls print port 8080 and bad port: 80a, and retry prints two failed attempts, then done after 3 calls. To run an async callback over an array, see async/await with array map.

7Which should you use?

MethodChecks the callbackBest for
(x: T) => RYesAlmost every callback: the default, inline or as a type alias
<T, U>(fn: (x: T) => U)Yes, linked to the other typesCallbacks over the caller’s data: map, filter, sort helpers
{ (x: T): R; prop: P }YesFunctions that also carry properties; interface style
onX(x: T): voidYes, but loosely even in strict modeMethods on classes; prefer property syntax for callbacks
FunctionNo: any arguments, returns anyNothing new; write a function type
anyNo: not even that it is callableNothing; use unknown and narrow if the input is truly unknown

Frequently asked questions

Should I define a callback type with type or interface?

Either works and they are interchangeable for a plain callback: type OnDone = (total: number) => void; and interface OnDone { (total: number): void } accept the same functions. Most code uses the type alias because it is shorter and reads like an arrow function. Reach for an interface with a call signature when the function also has properties, or when you want to declare several overloads.

What is the difference between Function and () => void?

() => void is a specific signature: TypeScript checks the arguments you pass when you call it and knows it returns nothing useful. Function is the type of any callable value at all; calls on it accept any arguments and return any, so a callback typed Function can be called with a string where it expects a number and nothing is reported. Use a function type, or (...args: never[]) => unknown when you really accept any function.

Why can I pass a callback with fewer parameters than the type declares?

Ignoring extra arguments is normal in JavaScript, so TypeScript allows it: a (item: string) => void fits where (item: string, index: number) => void is expected, the same way [1, 2].map((n) => n * 2) ignores the index. The reverse is an error, because the caller would not supply the extra argument: Target signature provides too few arguments. Expected 3 or more, but got 2.

Why does a callback typed as returning void accept a function that returns a value?

A void return type in a callback type means "the caller ignores the result", not "must return nothing". That is what lets you write items.forEach((x) => list.push(x)) even though push returns a number. The rule only applies to function types; a function declaration written with : void must not return a value.

Should the parameters of a callback type be optional?

Usually not. (done: number, total: number) => void already accepts callbacks that use fewer parameters, so the ? adds nothing for them. Make a parameter optional only when your code really calls the callback without that argument. Mark the callback itself optional with onDone?: (total: number) => void and call it with onDone?.(total). Calling a required callback type with too few arguments is an error: Expected 2 arguments, but got 1.

How do I get the parameter types of an existing callback?

Use the built-in utility types on the function type: Parameters<OnProgress> is the tuple [done: number, total: number] and ReturnType<OnProgress> is void. For a function value rather than a type, add typeof: Parameters<typeof logPercent>. See how to get the return type of a function in TypeScript for these utilities in detail.

Run it yourself

Open any of these in the full TypeScript editor to tweak, run and share.

TypeScript playground