Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...