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?
Any valid JavaScript is also valid TypeScript. This means that you can write literal JS in any place in your code.
TypeScript is known as an Object-oriented programming language whereas JavaScript is a prototype based language. TypeScript has a feature known as Static typing but JavaScript does not support this feature. TypeScript supports Interfaces but JavaScript does not.
To answer the original question: Yes, you can use Typescript instead of Javascript. The ts compiler compiles to js, and you can even choose which version of js to compile to. „Wrapper” is not a thing. TS is a language that is a superset of JS, but it is a language.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With