简体   繁体   中英

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?

ie is any .js file a valid .ts file?

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

Not any valid JavaScript code is valid TypeScript see my example below.

var testVar = 4;
testVar = "asdf";

TypeScript gives the following error: Cannot convert string to number. To make that work in TypeScript add ":any" like below.

var testVar: any = 4;
testVar = "asdf"

This happens because TypeScript noticed testVar is declared and in the declaration it is assigned a number and therefore it decides it should stay a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM