Validate javascript data type in runtime? Yes, Hello Type.

frustigor

frustigor

Posted on September 7, 2018

Validate javascript data type in runtime? Yes, Hello Type.

update: I have published tyshemo which contains the data type system inside, and more rationality.

Days earlier, I began to learn about Typescript. When I meet interface and generics, my mind is suddenly confused, "what's this? what's that?". As a frontend conservative weak type follower, I do not want to write such a lot of code which is not related to my bussiness logic. Later, I looked into Flow which is advocated by facebook, I feel so frustrated because it will be the trend.

However, they make our project code more complex but not resolve the data type checking in runtime. As a little jser, I am always broken by data from APIs. "TypeError: xxx property of undefined", "TypeError: xxx property of null", "xxx is not a function", "xxx has no 'slice' method"...

Is there a way to validate data type and object structure easily? Finally, I wrote one library: HelloType.

Survive from API data structure

Before you use the data from API, validate its structure by HelloType. Firstly, wrap a structure with HelloType's api method, then use the instance to assert:

If the parameter of put does not match BooksType, an Error will be thrown. In the function, after assert, you do not need to worry about any data type and structure, just use the data as you wanted.

Trace error without break program

If you just want to collect the error information and do not want to break the program process, use trace method:

It will not pay any effect on your render performance, because it is run asynchronously.

Strict mode

As your data which is posted to your server should must and should only has certain properties, use strict mode to check whether the data structure is right:

Becuase the first item of books has a additional property size, and strict mode used, assert will break the program.

There are more features, look into my github to find out your interests.

💖 💪 🙅 🚩
frustigor
frustigor

Posted on September 7, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Js | DataTypes |
javascript Js | DataTypes |

August 30, 2024

JS Data types (Ma'lumot turlari)
datatypes JS Data types (Ma'lumot turlari)

May 31, 2024

JavaScript
javascript JavaScript

May 28, 2024

Use Prisma with an SQLite DATETIME datatype
javascript Use Prisma with an SQLite DATETIME datatype

February 26, 2023