Why I prefer types

Whether it's PHP or JavaScript/TypeScript, I prefer type declarations in my code.

As well as benefits like auto-completion in your IDE or text editor and being able to more effectively statically analyse the code, to me, the code is more readable and easier to understand with the types included.

It's more to read, but I can do so easily and immediately know what a function expects as function arguments and what it will return.

Here's the code from my previous email on types from a few days ago, with and without the types declared:

add(...numbers) {
  // ...
}

subtract(...numbers) {
  // ...
}

add(...numbers: number[]): number {
  // ...
}

subtract(...numbers: number[]): number {
  // ...
}

Without types, I can infer what the function accepts and returns, but that's based on my assumption, which could be incorrect.

What if numbers was an array of strings of numbers - e.g. ['one', 'two', 'three'] - and what if instead of returning the result, it stored it in state to return from a different method like equals() or calculate()?

With the type declarations included, I don't need to presume, infer or make best guesses.

It's clear from just reading the code.

- Oliver

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.