0

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

1 Answer 1

2

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

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

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.