Reputation: 3816
We're planning to move on to Angular 2 and use TypeScript for it because of it's many advantages (readability, maintainability etc). After reading a few blogs on it, I came across this blog and the following piece of code. (left - typescript and right - equivalent JS code)
As per the documentation of TypeScript, we found that it does compile time checking for variables and gave a compile time error if the types are not matched.
So looking at the following piece of code from the above TS code
var firstBadAlien = new BadAlien('DrDobbsBadAlien',0,5000,5);
should give me a compile time error if I don't supply the exact type of arguments needed which is nice.
I have following questions:
What happens if this code runs dynamically on the browser and the user supplies wrong type of arguments. This will fail to check type since there's no type checking on the equivalent JS generated for that.
Does typescript does only compile type checking or is there a way to generate JS that will also do type checking on run time? So suppose I want the argument to be of type 'number' and it can add JS code to check for type like 'isFinite()' ?
Thanks.
Upvotes: 0
Views: 170
Reputation: 276303
What happens if this code runs dynamically on the browser and the user supplies wrong type of arguments. This will fail to check type since there's no type checking on the equivalent JS generated for that.
The assumption is that you will use TypeScript code to call your TypeScript code, and that will fail to typecheck. Anything else will just pass through. If you accept a boolean
from the user somehow, it will fail at runtime.
Does typescript does only compile type checking or is there a way to generate JS that will also do type checking on run time? So suppose I want the argument to be of type 'number' and it can add JS code to check for type like 'isFinite()' ?
Not yet.
Upvotes: 2