Fahad Ur Rehman
Fahad Ur Rehman

Reputation: 3

Typescript functions as optional parameters in another function

I have a function like this:

function fn(variableFunction: (args?: String) => boolean) { //changing to args?: any works but this needs to be String
  ...
}

I want to be able to pass the following functions to the above function.

function something(arg: string) {
  return true;
}

function something2() {
  return true;
}

fn(something); //doesn't like this because arg in something is not optional (and I don't want to make it optional either)
fn(something2);

What changes can I make to fn to make it work for both the cases?

TS Playground for the above issue

Upvotes: 0

Views: 49

Answers (1)

jcalz
jcalz

Reputation: 327624

The real answer depends on what you plan to do with variableFunction inside the implementation of fn. Assuming you want to actually call it on a string argument like:

variableFunction("hello");

Then the right signature for fn is

function fn(variableFunction: (args: string) => boolean) {
  variableFunction("hello");
}

Here, I changed String to string because you almost certainly don't mean the wrapper object String, and I made the args argument non-optional.

That will accept both fn() calls in your example:

fn(something); // okay
fn(something2); // okay

It may be surprising that fn(something2) is not an error, since something2 does not take an argument. But this is intentionally how TypeScript's type system works; functions of fewer parameters are assignable to functions of more parameters. That's because you can always treat something2 (a function of no parameters) like something (a function which ignores its parameters) at runtime.

Anyway, hope that helps; good luck!

Playground link to code

Upvotes: 2

Related Questions