Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Currently I have type definition as:

interface Param {     title: string;     callback: any; } 

I need something like:

interface Param {     title: string;     callback: function; } 

but the 2nd one is not being accepted.

like image 690
Smrutiranjan Sahu Avatar asked Apr 17 '15 03:04

Smrutiranjan Sahu


People also ask

How do you define a type of callback function in TypeScript?

Use Type Keyword to Declare Callback Type in TypeScript So with the help of the type keyword, you could declare your callback type as shown below. Copy type callBackFunction = () => void; This declares a function that does not take any arguments and returns nothing.

How do you define a function in type?

A function's type can be defined with (arg0: type0) => returnType and we can use this type definition in another function's parameter list.

How do you pass a callback function in TypeScript?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.


1 Answers

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.

like image 124
Ryan Cavanaugh Avatar answered Nov 18 '22 16:11

Ryan Cavanaugh