Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Higher order function types

Tags:

I'm getting really excited about TypeScript. How do you set the type of a function parameter?

function twoMoreThanYou(calculateANumber: Function):number {     return calculateANumber(4) + 2; }  function double(n:number):number {     return n*2; }  console.log("TWO MORE", twoMoreThanYou(double)) 

How can I type calculateANumber better? I'd like to specify that it must be a function that takes a number and returns a number.

Can I then make an "interface" or some shorthand for that type so I can make my higher order function signatures more readable?

like image 241
Sean Clark Hess Avatar asked Nov 06 '12 00:11

Sean Clark Hess


People also ask

What are higher-order functions in TypeScript?

A high order function is a function that can return another function, or you can pass a function as an argument, let's see this easy example: const laser = (intensity: number, f: Function ):string => `${intensity + f()}`console. log(laser(2, () => ' volts! ' )) // "2 volts!" Example High order function In TypeScript.

Is setTimeout high order function?

setInterval and setTimeout are two of the higher order functions in Javascript.

Are callbacks and higher-order functions the same?

Higher-Order Functions(HoF) and Callback Functions(CB) are different. Higher-Order Functions(HoF): A function that takes another function(s) as an argument(s) and/or returns a function as a value. Callback Functions(CB): A function that is passed to another function.


1 Answers

These both work

interface NumberFunction extends Function {     (n:number):number; }  function twoMoreThanYou(calculateANumber: (n:number)=>number):number {     ... }  function twoMoreThanYou(calculateANumber: NumberFunction):number {     ... } 
like image 78
Sean Clark Hess Avatar answered Sep 21 '22 02:09

Sean Clark Hess