TypeScript真的是JavaScript的超集吗? [英] Is TypeScript really a superset of JavaScript?

查看:271
本文介绍了TypeScript真的是JavaScript的超集吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用TypeScript,有时会遇到编译器错误使用未声明的变量。例如,以下工作在纯JavaScript中:

I just started using TypeScript and sometimes get compiler errors "use of undeclared variable". For example the following works in plain JavaScript :

var foo = {};
foo.bar = 42;

如果我尝试在TypeScript中执行相同的操作,它将无法正常工作,并在上面提到上述错误。我必须这样写:

If I try to do the same in TypeScript it won't work and give me the mentioned error above. I have to write it like that:

var foo :any = {};
foo.bar = 42;

在纯JavaScript中,带有any的类型定义既不是必需的也不是有效的,但在TypeScript中这似乎是强制性的。我理解错误及其原因,但我总是在视频中听到并在文档中阅读:

In plain JavaScript the type definition with any is neither required nor valid, but in TypeScript this seems to be mandatory. I understand the error and the reason for it, but I always heard in Videos and read in the documentation:

typescriptlang.org


TypeScript是JavaScript [...]的类型超集

"TypeScript is a typed superset of JavaScript [...]"

简介视频@分钟3:20


所有JavaScript代码都是TypeScript代码,只需复制并粘贴

"All JavaScript code is TypeScript code, simply copy and paste"

这是在TypeScript开发过程中发生了变化还是必须通过特定的编译器设置才能使其工作?

Is that a thing that changed during the development of TypeScript or do I have to pass a specific compiler setting to make this work?

推荐答案

TypeScript存在的原因是有一个编译器和语言可以比vanilla Javascript更好地强制执行类型。任何常规Javascript都是有效的TypeScript,语法。这并不意味着编译器必须完全满意它。 Vanilla Javascript通常包含在类型安全性方面存在问题的代码。这并没有使它成为无效的 TypeScript代码,但这正是TypeScript存在的原因,正是编译器的工作向你指出了这些问题。

The reason for TypeScript's existence is to have a compiler and language which can enforce types better than vanilla Javascript does. Any regular Javascript is valid TypeScript, syntactically. That does not mean that the compiler must be entirely happy with it. Vanilla Javascript often contains code which is problematic in terms of type security. That doesn't make it invalid TypeScript code, but it's exactly the reason why TypeScript exists and it's exactly the compiler's job to point out those problems to you.

语言本身仍然是彼此的子/超集。

The languages as such are still sub/supersets of one another.

这篇关于TypeScript真的是JavaScript的超集吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆