Is TypeScript really a superset of JavaScript?

Markus picture Markus · Apr 28, 2015 · Viewed 12.3k times · Source

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;

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;

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 is a typed superset of JavaScript [...]"

Introduction Video @minute 3:20:

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

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?

Answer

deceze picture deceze · Apr 28, 2015

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.