title: Dart: Type safety for function that takes a function with varying return value as a parameter
body: <p>I am trying to create a Dart function that essentially wraps other functions with some boilerplate error handling code, and otherwise returns the value returned by the original function.  A key requirement is that it should accept functions with multiple different return types, while avoiding duplicating the common error handling logic across multiple different functions.  I found one approach that seems to work by using the dynamic type, except that the compiler is not able to detect type mismatches, so they are only caught at runtime.</p>
  
  <p>Is there a better way to accomplish what I'm aiming for here, and particularly in a way that catches type mismatches at compile time?</p>
  
  <p>Below is a simplified example of my code, where the functions compile fine, but at runtime getAString will raise an error  <code>Dart Error: Unhandled exception: type 'List&lt;String&gt;' is not a subtype of type 'String'</code></p>
  
  <p>/// Signature of API function calls
      typedef APIFunctionCall = dynamic Function();</p>
  
  <pre><code>dynamic doWithErrorHandling(APIFunctionCall fn, {retries: 2}) async {
    for (int attempts = 0; attempts &lt; retries + 1; attempts++) {
      try {
        return await fn();
      }
      on Exception catch (e) {
        print(
            "This is just an example; actual function does a bunch of more specific error handling.");
      }
    }
  }
  
  Future&lt;String&gt; getAString() async {
    // Want a function that can support multiple return types but detect type errors
    String doesReturnAString =  await doWithErrorHandling(() async =&gt; 'hello world');  // This runs fine
    String doesntReturnAString = await doWithErrorHandling(() async =&gt; &lt;String&gt;['hello', 'world']);  // This throws an Error
    return doesntReturnAString;
  }
  </code></pre>