Category: PHP, api, javascript

The idea of creating a whole new language, primarily just to add types to Javascript, strikes me as a fundamentally bad idea given how many languages that compile to Javascript have fallen by the wayside. Flow seems like a much better approach since it adds types to the language rather than creating a new language, and I’ve been using it on my React components for a good while now.

However, it’s difficult to type the value of data correctly, since it will be different for different endpoints, and given that it may be reused for almost any endpoint, you can’t cover all the acceptable response types.

By passing in a polymorphic type using in the function declaration, we can then refer to that type when specifying what data should look like: Then, when calling the hook, we can define a type that represents the expected shape of the data (here called , and specify that type when calling the hook, as in this example: That way, we can specify a completely different shape for our response data every time we call a different endpoint, without creating a different hook for every different endpoint, and still enjoy properly typed responses from our hook.

Flow would then flag it as an error if you assigned an item of the wrong type to that collection, thus making some unit tests redundant.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners