Skip to content
Advertisement

Is any JavaScript code a valid TypeScript code?

Currently I’ve started to learn TypeScript. From the documents I’ve studied for TypeScript, I saw some samples that pure JavaScript code could be compiled as TypeScript code.

My question is: Is TypeScript language designed in a way that any JavaScript code will be a valid TypeScript code?

i.e. is any .js file a valid .ts file?

Advertisement

Answer

Let’s assume valid code means : is syntactically correct with respect to the language specifications.

Then the answer is YES.


It is written down in the TypeScript Specifications (second paragraph) :

TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 2015 (ES2015)syntax. Every JavaScript program is also a TypeScript program.

(emphasis mine)

Now, most often you don’t want basic JavaScript to be used “uncontrolled”. After all, that was one of the reasons to create the TypeScript language in the first place !

Nevertheless, a valid JavaScript program is technically valid TypeScript. This is in the specifications probably by need of “backward compatibility”, or, better formulated, by need of supersedence to ECMAScript


To take the example of another answer, the Typescript code

var testVar = 4;
testVar = "asdf";

will be transpiled into exactly the same JavaScript code (with all default compiler options)

Demonstration here on Typescriptlang.org playground

even though there is a TypeScript error, this doesn’t prevent a valid javascript to be output from there. It “compiles with error”. (I wish this was called a warning instead of error, but anyway).


See also : https://basarat.gitbooks.io/typescript/content/docs/why-typescript.html

Your JavaScript is TypeScript

TypeScript provides compile time type safety for your JavaScript code. This is no surprise given its name. The great thing is that the types are completely optional. Your JavaScript code .js file can be renamed to a .ts file and TypeScript will still give you back valid .js equivalent to the original JavaScript file. TypeScript is intentionally and strictly a superset of JavaScript with optional Type checking.

The simplest option that can deactivate this behavior (output js even though there are Type errors) is --noEmitOnError

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement