r/node • • Nov 10 '20

Conditionally call a function with optional chaining.

Post image
345 Upvotes

126 comments sorted by

View all comments

1

u/oguz279 Nov 10 '20

I prefer typeof fn === "function" && fn() as it covers cases where fn would have a truthy value but not be a function.

9

u/8lbIceBag Nov 10 '20

If you're getting even the type completely wrong something is broken.

1

u/Not_Sugden Nov 10 '20

unless you used a type of filter callback, and instead allowed just an object / string to be passed in?

interface OptionsForSomething {
    
    filter: ((x: string) => boolean) | string;
    
}

1

u/8lbIceBag Nov 10 '20

In this case, it'd be totally useless because nothing is being passed to the function. No this or argument. Which implies its scope and this are already bound. If you had a filter string, what would it be filtering against? There's no context.

For your scenario to be valid, the parent comment needed to be something like:
typeof fn === "function" && fn.call(ctx) or
typeof fn === "function" && fn(ctx)