TypeScript

TypeScript – Type Hint An Array Of Functions

TypeScript – Type Hint An Array Of Functions

I’ve been more verbose on adding types on my TypeScript codes lately as it tends to be very useful in future reading and refactoring. Recently, I needed to add a type hint to an array that contains functions and I have to add type hints to each parameters and return types as well. With a quick search, I found out I just have to wrap them in curly braces.

This is how it looks like if functions have no arguments and return types.

Note: Spacing is just my personal style and is not required.

const handlers: { () => void }[] = [
  function1,
  function 2
];

This is how it looks like with more types into arguments and return types.

const handlers: { (quota: QuotaDto, max: number, users: UserDto)=> QuotaDto }[] = [
  this.function1,
  this.function2,
];

It can get long really quick but it helps you find issues where one of your newer functions don’t meet the required argument types or return types.

That’s it! I wrote this post blazingly fast as I’m in a hurry!

Featured image by Pixabay.

No Comments

Leave a reply

Your email address will not be published. Required fields are marked *