Understand the Downsides of Overusing Primitive Types

Tomasz Ducin
InstructorTomasz Ducin
Share this video with your friends

Social Share Links

Send Tweet

Choosing the proper types to model your data in complex applications is important. Most of the time you'll reach for primitive types that get the job done well.

Primitive types have their downsides which we'll explore in this lesson. The main take away here is that when you have different kinds of a primitive type, you can start running into issues when processing that data. For example, an object's 'id' and a property on the object of 'salary' might both be of type number but you would never want to add these two values together.

[00:00] While working in highly complex applications, one of the challenges we can face is choosing the proper types to model our data. Most often, we're fine with using good old primitive values, for instance, representing an employee salary with a number type, especially when we just fetch the data and display it. However, the more [00:20] we process the data, the more bugs we can introduce values, which represent totally different things, such as employee salary, employee's age, or even employee's ID are of the same type, which is basically the primitive number. Let's see an example. It does make sense to perform an [00:40] operation on both employee salary and a project's budget since both values relate to the same type of data, which is essentially money. It also does make sense to include the offices, real estate, monthly rental. Still, this is money. However, technically, it's [01:00] absolutely valid and possible to include things which are totally unrelated, such as employees age. This is all technically number. To make things worse, we can add them, we can multiply, we can square or square root and perform many other operations. At a certain point of complexity, [01:20] many bugs could be caused because we allow the type system to perform operations on unrelated types, and simply it cannot find out what is meaningful and what is meaningless. Let's also declare a function that is going to find employees by skills. So this [01:39] function would find employees which include a certain skill. In our domain, the skill is being represented as a primitive type, again, just a string. And let's say that what we are going to return here is an employee. Technically, again, it is valid to search [01:59] the employees not by a skill, but by something totally unrelated like first name. And this could be a problem if there is a lot of data processing that is related to skills or money or whatever is important in your application. TypeScript enables many techniques to deal with these challenges.