javascript function parameter types code example

Example 1: typescript parameter function type

class Foo {
    save(callback: (n: number) => any) : void {
        callback(42);
    }
}
var foo = new Foo();

var strCallback = (result: string) : void => {
    alert(result);
}
var numCallback = (result: number) : void => {
    alert(result.toString());
}

foo.save(strCallback); // not OK
foo.save(numCallback); // OK

Example 2: typescript function as parameter

function createPerson(name: string, doAction: () => void): void {
  console.log(`Hi, my name is ${name}.`);
  doAction(); // doAction as a function parameter.
}

// Hi, my name is Bob.
// performs doAction which is waveHands function.
createPerson('Bob', waveHands());

Example 3: javascript function multiple parameters

function sum(...values) {
    console.log(values);
}
sum(1);
sum(1, 2);
sum(1, 2, 3);
sum(1, 2, 3, 4);


function sum(...values) {
    let sum = 0;
    for (let i = 0; i < values.length; i++) {
        sum += values[i];
    }
  
    return sum;
}
console.log(sum(1)); //1
console.log(sum(1, 2)); //3
console.log(sum(1, 2, 3)); // 5
console.log(sum(1, 2, 3, 4)); //10

Example 4: how to access any argument in javascript

function example() {
	console.log(arguments);
  	console.log(arguments[0]);
} // Console outputs an array of each argument with its value

example('hi', 'hello'); 
// Outputs: 
// ['hi', 'hello']
// 'hi'