TypeScript has rapidly grown in popularity in the last few years, and with good reason. It takes a rather flexible language in JavaScript, and fixes one of the big weaknesses of the language, being descriptive typing, with very little compromise having to be made.

However with that increase in popularity comes a big challenge, how to use the language to its full potential. That’s a big challenge. I’m learning some new feature, or way to use TypeScript, almost every week.

A large percentage of TypeScript users come from an Object Oriented background, and therefore naturally draw parallels between TypeScript and the OOP languages they used, particularly languages like Java and C#. However, this mindset can lead to us overlooking very useful features of TypeScript. With this article, I hope to demonstrate how TypeScript differs from those languages, and how we have to change our thinking to extract more from the language.

It’s not about Classes.

First thing’s first, TypeScript is not OOP. TypeScript provides the ability to add Types, which in their own words:

provide a way to describe the shape of an object […] allowing TypeScript to validate that your code is working correctly

Classes exist in JavaScript already. Therefore you can utilise classes in TypeScript too. But Classes are not Types. Classes can, and usually do, define behaviour. Types do not. Types are simply a contract.

A seemingly simple problem

I’ve encountered a few problems over the past few weeks that have demonstrated good uses of Union Types. I will start with a seemingly simple problem:

In my system I am writing, I have two types of Authentication, one for systems, and one for users. I have two different ways of dealing with this, and two different places to look up accounts. It is therefore important I establish which of account it is. My authentication middleware does this work for me, and adds the information to the request for use later on in the pipeline.

#pburgess #tech #typescript

Getting The Most Out Of TypeScript - Union Types
1.30 GEEK