1

I am trying to pass a function pointer into an existing function in Typescript. The below should work, but when calling agreet() I receive undefined, why?

function greeter(greetFuncPtr) {
  console.log(greetFuncPtr); // returns ƒ () { greet(); }
  console.log(greetFuncPtr()); // returns undefined
  console.log(greet()); // returns "Hello"
  return greetFuncPtr();
}

function greet() {
  return "Hello";
}


document.querySelector("#app").innerHTML = greeter(() => { greet(); });

See fiddle here https://jsfiddle.net/17w246uz/

4
  • Just pass greet. greeter(greet) Commented Jul 9, 2019 at 8:47
  • 1
    You not return anything => {return ...} Commented Jul 9, 2019 at 8:47
  • @Estradiaz yes right you are! A bit of blind sight. Funnily enough I did it right in the JS Console in Chrome :/ Long day... Commented Jul 9, 2019 at 8:51
  • @tkausl thanks, that's much neater Commented Jul 9, 2019 at 8:51

2 Answers 2

4

The syntax you use in the arrow function implies that the result of greet is not returned by the arrow function, to return it you would need to use a return

function greeter(agreet: () => string) { 
    console.log(agreet); // returns ƒ () { greet(); }
    console.log(agreet()); // returns undefined
    console.log(greet()); // returns "Hello"
    return agreet();
}

function greet() {
    return "Hello";
}


greeter(() => { return greet() });

Or not use the {}:

greeter(() => greet());

Or pass the function directly :

greeter(greet);

Note The type I added to agreet would have prevented the error in the first place, since you would have gotten an error that the passed in arrow function returned void instead of string

Sign up to request clarification or add additional context in comments.

Comments

1

In the arrow function you pass by calling greeter(() => {greet()}), you are missing a return statement. Hence, it returns undefined.

The simple fix is to a) add a return statement, or b) remove the curly brackets:

function greeter(agreet) {
  return agreet();
}

function greet() {
  return "Hello";
}


console.log(greeter(() => {return greet()}));
console.log(greeter(() => greet()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.