简体   繁体   English

将打字稿编译为javascript时,包括严格输入

[英]Include strict typing when compiling typescript to javascript

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. 我正在编写TypeScript代码,然后将其编译为Javascript,并直接从浏览器对Javascript(而不是Typescript)进行几个动态函数调用。 When you write a TypeScript function with type annotations, it will throw an error if something is of the wrong type. 当您编写带有类型注释的TypeScript函数时,如果某些错误的类型将引发错误。 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? 是否有任何选项可以对其进行编译并在函数的入口点添加类型检查?

Yes, there is a way to have runtime type checking - but you would have to use TS* rather than TypeScript. 是的,有一种方法可以进行运行时类型检查-但您必须使用TS *而不是TypeScript。 TypeScript erases all type information during compilation to leave you with clean JavaScript code. TypeScript会在编译过程中擦除所有类型信息,从而为您提供干净的JavaScript代码。

Gradual Typing Embedded Securely in JavaScript introducing TS* - a gradually type-safe language within JavaScript. 在JavaScript中安全地进行渐进式打字,引入了TS * -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. 这个想法是,编译将对您的代码进行重大转换,这不是他们在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. 除非您确实必须这样做(也许出于白皮书中描述的安全性原因),否则您最好使用TypeScript提供的更为主流的设计时和编译时检查。

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. Typescript不支持发出类型检查代码,需要使用instanceof,typeof等手动添加所需的任何类型检查。就像处理普通JS一样。

There has been talking of adding it as an optional flag, but as of 1.0.3 there is no flag. 一直在谈论将其添加为可选标志,但是从1.0.3开始,没有标志。

TypeScript really only provides compile-time type checking, but always compiles to type-less JavaScript. TypeScript实际上仅提供编译时类型检查,但始终会编译为无类型的JavaScript。

If you are concerned about run-time type checking, you can add your own calls to typeof or instanceof to make the checks. 如果您担心运行时类型检查,则可以将自己的调用添加到typeofinstanceof进行检查。 http://javascript.info/tutorial/type-detection http://javascript.info/tutorial/type-detection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM