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

查看:37
本文介绍了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 [...]"

介绍视频@minute 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 存在的原因是拥有一种编译器和语言,可以比普通 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天全站免登陆