使用打字稿

Working with TypeScript

我们计划继续使用 Angular 2 并为此使用 TypeScript,因为它有很多优点(可读性、可维护性等)。在阅读了一些关于它的博客之后,我遇到了 this blog 和下面的一段代码。 (左 - 打字稿和右 - 等效的JS代码)

根据 TypeScript 的文档,我们发现它会在编译时检查变量并在类型不匹配时给出编译时错误。

所以从上面的TS代码来看下面这段代码

var firstBadAlien = new BadAlien('DrDobbsBadAlien',0,5000,5);

如果我没有提供所需的确切参数类型,应该会给我一个编译时错误,这很好。

我有以下问题:

  1. 如果此代码 运行 在浏览器上动态运行并且用户提供了错误类型的参数,会发生什么情况。这将无法检查类型,因为没有对为此生成的等效 JS 进行类型检查。

  2. typescript 是只做编译类型检查还是有办法生成 JS 也会在 运行 时间做类型检查?所以假设我希望参数的类型为 'number' 并且它可以添加 JS 代码来检查类型 'isFinite()' ?

谢谢。

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.

假定您将使用 TypeScript 代码来调用您的 TypeScript 代码,这将无法进行类型检查。其他任何东西都会通过。如果您以某种方式接受用户的 boolean,它将在运行时失败。

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()' ?

还没有。