Q:

typescript function as parameter

// Default Parameters
sayHello(hello: string = 'hello') { 
    console.log(hello); 
}

sayHello(); // Prints 'hello'

sayHello('world'); // Prints 'world'
5
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
2
// define your parameter's type inside the parenthesis
// define your return type after the parenthesis

function sayHello(name: string): string  {
  console.log(`Hello, ${name}`!);
}

sayHello('Bob'); // Hello, Bob!
2
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()); 
1
function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
  const name = first + ' ' + last;
  console.log(name);
}

sayName({ first: 'Bob' });
1
function add(x: number, y: number): number {
  return x + y;
}
0

New to Communities?

Join the community