1

I am trying to build a shape where key is string and value is function. This works fine for regular functions but gives error for async functions. Following is what I am trying to do

  const type TAbc = shape(
    'works' => (function (): string),
    'doesnt_work' => (async function(): Awaitable<string>)
  );

This results in error A type specifier is expected here.Hack(1002)

Encountered unexpected text async, was expecting a type hint.Hack(1002)

Is this illegal in Hacklang? If yes then would like to know why?

Abhishek Jha
  • 935
  • 2
  • 10
  • 22

1 Answers1

1

async function (): T is illegal in Hacklang. The suggested way to do this is by defining it in the return type, Awaitable<T>.

So to get this working we can do this

const type TAbc = shape(
  'sync' => (function (): string),
  'async' => (function(): Awaitable<string>)
);

And while initialising an instance of this type we can internally call an async function. For eg:

$abc = shape(
'async' => function(): Awaitable<string> {
  return someAsyncFunction();
});
Abhishek Jha
  • 935
  • 2
  • 10
  • 22
  • 1
    Correct. You can also pass the function directly to your "async" field using [a function reference](https://docs.hhvm.com/hack/functions/function-references) like: `$abc = shape('async' => someAsyncFunction<>);` – concat Aug 19 '21 at 17:37
  • 1
    The reason that `async` is illegal in a *type* definition is that it's irrelevant that the function is async or how it's implemented. All that matters is that the return type is `Awaitable`. This is the same reason you can't declare a function `async` in an interface, nor can you declare an `abstract async` function in a class. – Josh Watzman Aug 21 '21 at 14:39