Runtime Type Casting in JavaScript

Muhammet Ali AKBAY
The Startup
Published in
4 min readJun 28, 2020

JavaScript is one of the best programming languages for developing frontend applications. It has dynamic typing which makes it a perfect match when you need to develop applications in a (relatively) shorter period of time. And of course, tons of libraries and tools which they are written with JavaScript makes it strong and popular. But…

But every good thing has a “but”. The “but” of JavaScript is one of what makes it populer, dramatically. …dynamic typing feature of JavaScript makes it unsafe for backend applications which they do many communications to the frontend side. When a request recieved by the backend, structure of request must be validated and “cast”ed to the desired/allowed data type. To make this kind of checks is easliy possible in strictly typed languages like Java or C#. At this point you may think that “TypeScript is developed for exactly this purpose”, but actually not. TypeScript provides only compile time checks for data types. It can not help us for incoming data from out of program’s own memory, e.g. network, user input, config files etc.

Skip these paragraphs. Really. I just wanted to talk more. 😏

Don’t worry, JavaScript provides some “essential” ways to apply some “essential” type checks. It can check that if the data is string, number, null, undefined, array etc. using “typeof” or “instanceof” keywords. “But”, while these keywords let us able to build complex type checkings, they are not enough themselves. To make program check that if each field of an object fits into desired structure or that if elements of an array is assignable to some specific type requires many many if-else statement sequences and many many code duplications. Remember,

Don’t repeat yourself.

There must be a module already written. And there is. (At least, there is anymore.)

“structure-check” library is here to help you on these kind of requirements.

Let’s write some code. Assume that we have a server side application which receives some requests from client via any network protocol.

See that there is no problem since the request payload is an object and contains desired fields, “title” in this example. But what if some “curiosity” person try to feed our server with some unexpected payload?

Obviously, this will mess up the entire logic of the server side code. Absolutely any backend programmer adds some lines to check incoming data types. Let see how to do that.

Adding some manual checks on the incoming data will make us sure that no unexpected data passing into the logic. Until here, i just wanted to show you how to do the type checks in JavaScript 101 grade.

Now, let me show you how to do the same thing easier way and without code duplications. Using structure-check package ofcourse.

In the example above, “DesiredMessage” constant holds a function which contains a pre-generated structure check logic. When you call it by passing the input data as parameter, it performs the desired type checks and returns true if the data fits into it, false otherwise.

And a shorter way is to use “.cast(<data>)” method which makes us sure that input data fits into the structure by throwing a “TypeCastException” when it doesn’t fit.

“.cast” method takes a input data as parameter and checks if it fits in the structure. If it ok, this means there is no problem to return the data to keep logic flowing. But otherwise, the method throws a “TypeCastException” to break logic flow before any failure or bug being produced.

Let’s make the things more complex.

The previous examples were a little bit simple. You may still thinking that there is no need to use a new library to get free from a few lines. You may right, until now. Think that, the structure gets more complex day by day of developing the application. You are developing new api actions every day and ofcourse count of different input data types gets increasing one by one. And eventually you will need to write tons of if-else-typeof-instanceof statements to keep logic free of security bugs.

Here is an example of solving these kind of validations for such a complex structures, written using “structure-check”.

Let’s talk about security of “Auth” on this example. If a request contains a field with name “auth” and value matching Auth structure, we can filter it just a single line of code:

if (AuthRequired(message))

And can check the token inside of this branch, if supplied any by client. Then, it is time to check the structure of remaining message data. If whole data fits in “DesiredMessage” structure, we allow it to pass into our logic. After this point, there is no suprise of tricky fields or data supplied from client, “structure-check” guarantees that for us. As an example, if message is a “PostAction” and with “share” action value, it must be having “auth” field containing “RegisteredPersonWithToken” value. It would not pass into rest of logic otherwise. And ofcourse the auth token gets validated as i described before.

“structure-check” is written in TypeScript, and it is fully compatible with compile time types. More examples are coming soon.

Please don’t hesitate to contact me about anything, i am in love with discussing about codes. 🥰

--

--