How can I create the type from existed function in Dart/Flutter?

I know typedef can create custom type, something like:

typedef Custom<T> = int Function(T a, T b)

But if I have a function from the dependency and want to create the type for arguments, how can I do this?

int functionFromDependency(String a, {int b, ComplexType c}) {
  // ...
}

// something syntax like `typeof<functionFromDependency>`
void myProcess(typeof<functionFromDependency>? runner) {
  (runner ?? functionFromDependency)(
    a,
    b: b,
    c: c
  );
}

It is helpful for testing which can inject custom function.


Solution 1: jamesdlin

Dart doesn't have something like C++'s decltype that would allow you to statically re-use the type of some other variable.

In the case of a callback argument to a function, I don't think that it would make sense anyway. For example, you could give up static type-checking and do:

void myProcess(Function? runner) {
  (runner ?? functionFromDependency)(
    a,
    b: b,
    c: c
  );
}

but ultimately myProcess still requires that runner be a function that can takes a single positional argument and that can take named parameters b and c, all with types appropriate for the supplied arguments. You might as well do:

typedef MyProcessCallback = void Function(A a, {B b, C, c});

void myProcess(MyProcessCallback? runner) {
  ...
}

myProcess should not be trying to conform to its callers; that's backwards. Callers of myProcess should be conforming to myProcess's API instead, which is much easier.