TypeScript 100.0% 是如何用 TypeScript 编写的?

GitHub 上的 TypeScript 存储库中,根据 GitHub,存储库只包含100.0% 的 TypeScript (. ts 文件)

enter image description here

它是如何工作的? TypeScript 是如何自己编译成 JavaScript 的?

10051 次浏览

This is called compiler bootstrapping and is common for a number of reasons, not least of which is the language you're writing is often the best-suited language for understanding the concepts you're implementing in the language you're writing...

If you take a look at the article, most major languages have self-hosting compilers (C, C++). Doing so means you're running a large amount of code through your new compiler, which is a good test of functionality. In the usual case, you're writing a compiler because you want a new language with some benefit over your current language, so being able to take advantage of those benefits while writing the compiler makes good sense.

The very first pass will have to be written in an existing language, but once you have a compiler, you can use that to compile the next revision and so on. Obviously this limits your compiler to only using features from the n-1 revision, but since you control the compiler that should be a minor issue. Quoting Wikipedia:

The main parts of the C++ compiler clang were written in a subset of C++ that can be compiled by both g++ and Microsoft Visual C++.

Since TypeScript is a superset of JavaScript, the compiler could (theoretically) be written in the shared syntax and compile under either. I don't believe that's the case here, but the relationship does give you a good starting language for the initial compiler.

Typescript is self-hosting and maintains a Last-Known-Good (LKG) version of itself to compile the next version. Currently (30/08/2016) that version is in the lib directory.

I just want to add something that I think is interesting.

In git you can have a file called .gitattributes. Github has a project called linguist which can make use of that file for their language details section in every repository. In the typescript repo there is a .gitattributes file which has the following content:

*.js linguist-language=TypeScript
* -text

You can fork the typescript repo, remove that file, commit to github and wait for some time while their repository analysis job completes and the language graph will change.typescript repo language stats without gitattributes