Not so long ago i was tormented by the idea of typing on JS. Not because it is the new hype in the community but because I could imagine what are the benefits of such implementation.

Even on a small to medium project that constantly grows using react-redux you could see that you must go from reference to reference to understand how an action was called. Even on testing this creates a big headache especially when you are trying to test code that you didn’t write. On top of that the safety that type checking gives you when lots of the errors will pop up when you will develop the app.

So i thought i could dive into it a bit deeper so i could get a realistic idea of what that would be and implement based on my findings.

JS TODAY

Before diving into the deep water lets first think what we are trying to solve. JS is a not a strongly typed language, but because of that it can give everyone the opportunity to build an application fast without problems.

But JS best strength can become its weakness really fast.

Although its not a strongly typed language JS defines seven built-in types .There is an argument here on how these are called, types, tags or subtypes but let’s stick with the types. Those types are the following

null

undefined

boolean

number

string

object

symbol -- added in ES6!

We can see that these types are what they are claim to be using typeof . Here and at the very start of my investigation you can see the problem. When the bellow seems fine, there is always a .. but.

typeof undefined === "undefined"; // true

typeof true === "boolean"; // true

typeof 42 === "number"; // true

typeof "42" === "string"; // true

typeof { life: 42 } === "object"; // true



// added in ES6!

typeof Symbol() === "symbol"; // true

But what about null?

typeof null === ???;

Null is a very special and buggy case, because its type is object … I know it look horrid right? But hold on a second, there is more.

Even with built-in functions like (Boolean, String, Array etc) you can find limitations. See the example below

var testVar = “i dont need types” === string

var testVar = new String(“i don’t need types”) === object var testVar = false === boolean

var testVar = new Boolean(false) === object

You can see that if you create a variable with a boolean or a string that type corresponds to what you passed. In the other hand if you created those with built-in function their type is object.

If that wasn’t weird enough i have gathered some more examples to convince you.

10 + 5 === 15

'10' + 5 === '105'

'10' - 5 === 5

( + '10') === 10

So, you can’t count on your own numbers.

I know how that feels!

Need of types

So based on the above examples there is clearly the need of types. Is it easy though?