TypeScript: The Type Experiment

Nicos Tsourektsidis
2 min readJul 15, 2022

--

The Type Experiment: Can you spot the JavaScript errors?

Read the following JavaScript code and try to spot any mistakes:

const favorites = {
tracks: [],
totalLength: 0,
};
function addToFavorites({ title, artist, album, length }) {
favorites.tracks.add({ title, artist, album, length });
favorites.totalLength = favorites.totalLength + track.length;
}
const track = {
title: 'Bohemian Rhapsody',
artists: ['Queen'],
album: 'A Night At The Opera',
length: '5.45m',
};
addToFavorites(track);

Some of you may think to copy this snippet and paste it into your browser’s console. I want to save you from this extra effort; this code has zero JavaScript errors. It compiles perfectly!

Now, without reading the solution below, pause for a minute and try to spot any potential issues.

The solution follows.

No peeking!

The Solution

Let’s copy that code snippet to our TypeScript file to see what we will get.

Yup! As expected, we do have a couple of issues in this code…

This code will not work, but believe it or not, it is perfectly legit in JavaScript. By that I mean that technically we are not violating any of the compiler rules.

Not even strict mode can save us here.

Of course, TypeScript inferred the types and quickly identified the errors:

  • At line #7, we are using an array method that doesn't exist. The correct method is push() not add().
  • At line #8, we are adding a string '5.45m' to the number 0. Again, this is valid JavaScript code. The JavaScript compiler will automatically coerce the number to a string and the result will be '5.45m', which is far ahead of what we wanted to achieve here.
  • Ultimately, at line #13, we have a typo in the property name artist, which must not be plural.

Want to watch the explanation in a video?

It’s part of my ✨ free course for TypeScript ✨. I teach everything I know about the language, with practical examples and a lot of fun! 🤗

Prefer to reading instead? Check out my full article, in which I explain all these in detail. I also write about my experience learning the language.

And trust me, I was also late on this as much as you are.

Happy coding!

I have much more content in the pipeline for TypeScript.

--

--

Nicos Tsourektsidis

Lead Software Engineer @ Epam Systems Switzerland. I ❤️ JavaScript, React, User Interfaces, coffee and video games.