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.
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.
If you just want to collect the error information and do not want to break the program process, use
It will not pay any effect on your render performance, because it is run asynchronously.
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.