Write Beautiful OO Classes with TypeScript

Plain ES6 Class

We can start with a plain ES6 class, and build our TS code on top:

Adding Some Type Safety

Let’s add some TypeScript to our example and see what we get:

Keeping Our Properties Private

That’s better! Now we can at least know that name is a string and not an array or something else… but name is still a public property of User. In fact, all properties in TypeScript classes are public by default. Let’s change that:

Get Rid Of Some Boilerplate Code

Note that in the last snippet, we first declared name as a private property of type string (line 2), then we declared it as an argument to our constructor (line 4), and finally, we assign the argument as a property (line 6). That’s a bit verbose, and we can have shorter and cleaner code by using a nice feature of TS called Parameter properties. In short, parameter properties are syntactic sugar that allows us to squeeze the three declarations we mentioned above into one line.

Getters and Setters

Now, let’s add a way to get and set the property name. The simplest way of achieving this would be to create two new methods: getName() and setName(name: string). That would work just fine, but we might want to provide a nicer API. Sometimes, it just feels more intuitive to write user.name = "Groot" instead of user.setName("Groot"). Luckily for us, TypeScript allows us to do exactly that using the set and get keywords. Here is what it will look like:

Properties of the Class Itself

So far, we have only worked with properties and methods that belong to the instance, meaning the object that is created by the constructor. TypeScript allows us also to define properties and methods that belong to the class itself, by using the keyword static. Static properties can be accessed by prepending the name of the class to the name of the property.

This Will Never Change

We know that some of the properties we define will never change. Sometimes, we even rely on the assumption that a particular property will always stay the same once we set it. If, for example, we identify users by email, then we don’t want other coders working on this class to change this field. It might be a good idea to mark this property as readonly, so the TypeScript compiler won’t allow any changes to the property email outside the constructor.

What Have We Accomplished

Ok! We’ve made some progress with our class. Here is what we have up to this point:

Iqoqo Engineering

Things we learn on our way

Idan Dardikman

Written by

There's no magic, it's just code you don't yet understand

Iqoqo Engineering

Things we learn on our way