It’s my third post about Angular2 and TypeScript as I’m creating an admin console for OctoPerf load testing platform.
This article explains how to set a type for callbacks. If, like me, you are used to AngularJS you may often use callbacks for asynchronous calls, typically for HTTP requests.
In Angular2 / TypeScript
In TypeScript it’s a bit more complicated, but cleaner.
First I need to define my customer:
Then the method getCustomers of the StripeClient service:
This method uses the Http Service to call the Stripe API. It has only one parameter: the callback function.
The type for the callback is
(customers: Customer)=>void a method that takes a Customer array as a parameter and returns nothing.
I don’t know why be we have to give a name to our customers array.
This method simply calls its callback with the customers returned by the API call.
We need to cast the result when doing so:
Stripe returns paginated lists, and we need to make successive calls to their API to get all our customers, plans, etc. It’s a good scenario to learn more about generics in TypeScript.