Reputation: 7416
I'm writing TypeScript code that is then compiled to Javascript, and several dynamic function calls are made directly from the browser to the Javascript, not the typescript. When you write a TypeScript function with type annotations, it will throw an error if something is of the wrong type. For example, the simple function
function add(a: number, b: number): number{
return a + b;
}
is compiled to the type-less
function add(a, b) {
return a + b;
}
Is there any option to compile it and add type-checking at the entry point of the function?
Upvotes: 0
Views: 399
Reputation: 250842
Yes, there is a way to have runtime type checking - but you would have to use TS* rather than TypeScript. TypeScript erases all type information during compilation to leave you with clean JavaScript code.
Gradual Typing Embedded Securely in JavaScript introducing TS* - a gradually type-safe language within JavaScript.
The idea is that the compilation would make major transformations to your code, which isn't something they have been keen to do in TypeScript.
Unless this is something you really must have (perhaps for the security reasons described in the white paper) you may be better off with the more mainstream design-time and compile-time checks offered by TypeScript.
Upvotes: 1
Reputation: 43698
TypeScript really only provides compile-time type checking, but always compiles to type-less JavaScript.
If you are concerned about run-time type checking, you can add your own calls to typeof
or instanceof
to make the checks. http://javascript.info/tutorial/type-detection
Upvotes: 0
Reputation: 1419
Typescript does not support emitting type checking code, any type checking that is needed will need to be manually added using instanceof, typeof, etc. Just as you would for plain JS.
There has been talking of adding it as an optional flag, but as of 1.0.3 there is no flag.
Upvotes: 0