In this article we’ll be going over just three reasons for using classes instead of constructor functions when building objects in Typescript.
Before diving into details, I’m just going to list them out. They are, in no particular order:
- Classes are easier to understand
- Classes are more common
- Classes enforce the usage of
So what does that even mean?! Let’s go over them in detail.
Classes are easier to understand
A common, and honestly probably the best, reason for using classes in Typescript, is that it is much easier to read and understand classes. Well, at least for most people it is.
Making it easier to read and understand means less time spent reading code in order to figure out what it does.
As classes often reuse method names across a codebase (and often across codebases too) it becomes really easy to tap into a new area of an application and quickly understand what it does.
While it seems a simple advantage to have something be more readable, it is an extremely important metric. As developers we spend a healthy portion of our time reading and understanding code, especially if we are new on a project or exploring new areas of an application.
Having it be intuitive and easy to read is a big win.
Especially when tied into the next point..
Classes are more common
I get it I get it! You may already be thinking, “but Martin, that’s a horrendous argument!”, and sure it very well could be. But there are many advantages to doing things the common way.
First of all, if everyone else is doing it the same way, then everyone else is running into the same problems that you are. That means it will be significantly easier to debug and solve issues that inevitably occur as are you are building.
Any object can inherit any object.
That’s why classes are helpful!
When they’re common, they are easier to read (see section 1), and simpler to extend and maintain.
It may not be sexy, but consistency is king.
'use strict'; when working with them through Typescript.
This is particularly good, because this is a recommended setting for configuring the Typescript compiler and ships by default. So you will see this in most projects and it causes the code to behave in a particular way.
When things behave in a particular way, they are predictable, and predictability is once again what allows us, as developers, to ship code with fewer bugs.
That’s a wrap
That’s it! Those are (currently) my top three reasons for using classes in Typescript, as opposed to constructor methods.
Do you have other reasons? Do you prefer constructor methods?