Home > Net >  Syntax for writing a function that returns a function
Syntax for writing a function that returns a function

Time:09-28

I'm just confused about how to write this. I have a simple function that returns another function (written in TypeScript):

public myFunction(): (arg1: number) => number {

......

I'm trying to write it as a regular function (function declaration), and not an arrow function, and confused about the correct syntax. Could someone please tell me what is the correct syntax to write it?

Thanks in advance

CodePudding user response:

myFunction(): ((arg1: number) => number)

The above statement doesn't mean its arrow function. Basically (arg1: number) => number) means, It's a function with one parameter number data type and its function return type is number.

To avoid confusion you can add function type and use it.

type SomeFunction = (a: number) => number;

myFunction(fn: SomeFunction) {
...
}

CodePudding user response:

A function that returns a function:

function foo(): () => void {
   return function() { }
}

Or:

function foo(): () => void {
   return () => {}
}

The return type for this function is () => void. The fact that this has an 'arrow' in it doesn't mean you have to return an arrow function.

  • Related