How to define type for a function callback (as any function type, not universal any) used in a method parameter How to define type for a function callback (as any function type, not universal any) used in a method parameter javascript javascript

How to define type for a function callback (as any function type, not universal any) used in a method parameter


The global type Function serves this purpose.

Additionally, if you intend to invoke this callback with 0 arguments and will ignore its return value, the type () => void matches all functions taking no arguments.


Typescript from v1.4 has the type keyword which declares a type alias (analogous to a typedef in C/C++). You can declare your callback type thus:

type CallbackFunction = () => void;

which declares a function that takes no arguments and returns nothing. A function that takes zero or more arguments of any type and returns nothing would be:

type CallbackFunctionVariadic = (...args: any[]) => void;

Then you can say, for example,

let callback: CallbackFunctionVariadic = function(...args: any[]) {  // do some stuff};

If you want a function that takes an arbitrary number of arguments and returns anything (including void):

type CallbackFunctionVariadicAnyReturn = (...args: any[]) => any;

You can specify some mandatory arguments and then a set of additional arguments (say a string, a number and then a set of extra args) thus:

type CallbackFunctionSomeVariadic =  (arg1: string, arg2: number, ...args: any[]) => void;

This can be useful for things like EventEmitter handlers.

Functions can be typed as strongly as you like in this fashion, although you can get carried away and run into combinatoric problems if you try to nail everything down with a type alias.


Following from Ryan's answer, I think that the interface you are looking for is defined as follows:

interface Param {    title: string;    callback: () => void;}