Reputation: 14046
With TypeScript or Facebook's Flow(type) I can statically type variables like
function add (x: integer, y: integer) { ... }
Both TypeScript and Flow catch any illegal invocation such as add('1',0)
at compile time.
However, when the library is compiled and exported, the types are gone. That means, the library consumer using that function gets no errors, that may potentially lead to hard-to-debug problems.
Is there any way to auto-generate additional code that would throw exactly the same errors at run time?
I can surely manually place guards every time a typecheck is expected but that feels boring and repetitive.
Upvotes: 3
Views: 2622
Reputation: 4983
You can also try babel-plugin-runtyper that performs type checking in runtime and does not require manual annotations.
For your example, if function looks like:
function add(x, y) {
return x + y;
}
And you call it as
add('1', 0);
you will get warning in console:
Plus operation with different types: "1" (string) + 0 (number)
Upvotes: 1
Reputation: 2943
https://github.com/codemix/babel-plugin-typecheck does what you want.
There is also https://gcanti.github.io/flowcheck/ but it looks a bit abandoned.
I haven't personally used any of those libraries. It seems that they might cover less than 100% of Flow syntax.
Upvotes: 3
Reputation: 164147
You won't get that from javascript alone regardless of which you choose as javascript doesn't have the notion of types in this sense.
I've never worked with fb flow so I can't reply on that, but typescript-wise here are the options I think you have: (in order of complexity and how much it doesn't make sense)
Modify the typescript compiler to automatically add runtime parameters validation
You can use the compiler API and inject a piece of code that validate the params for the functions. The compiler will tell you what the param names and types are, if they are optional and so on.
I'm just including this as an option but it's a pretty messed up solution in my opinion.
Start every function with validation
Pretty much like the previous one, just that you'll include the code yourself in each function instead of modifying the compiler to do so.
You can have a global function that take as arguments the meta data of the declared params and the actual arguments that are passed.
This will make things pretty ugly code-wise, and won't be fun to maintain.
In case of classes you can use decorators
The decorators feature is pretty new, but typescript lets you use it, and if you want to do this validation thing on classes then this is the best solution for your problem so far.
Generate a definition file for you library
This is the best of options if you ask me.
You don't need to contaminate your code with checks in each function. More than that, you can never control who's using your lib or how they use it so it's lost cause to even try.
For this your lib consumers will need to write in typescript themselves.
Upvotes: 1