The TypeScript language is internally divided into three main layers. Each of these layers is divided into sublayers or components. In the following diagram, we can see the three layers and each of their internal components. These layers are:
- Language
- The TypeScript Compiler
- The TypeScript Language Services
1. Language
It includes the components of the TypeScript language. This encompasses aspects such as syntax, keywords, and type annotations.
2. The TypeScript Compiler
The TypeScript compiler (TSC) converts a TypeScript program into its corresponding JavaScript code. Additionally, it carries out the parsing and type checking of our TypeScript code into JavaScript code.
Web browsers are unable to execute TypeScript code directly. Therefore, any program developed in TypeScript needs to be translated into equivalent JavaScript code that can be executed directly within the browser environment. To facilitate this process, TypeScript includes a compiler known as "tsc." The latest iteration of the TypeScript compiler, by default, supports ES6 and is capable of compiling source code into various module formats such as ES6, SystemJS, AMD, and others.
The TypeScript compiler can be installed either locally, globally, or through both methods using any npm package. After the installation is finished, we can compile the TypeScript file by executing the "tsc" command in the command line.
Example:
$ tsc helloworld.ts // It compiles the TS file helloworld into the helloworld.js file.
Compiler Configuration
The configuration for the TypeScript compiler is specified in the tsconfig.json file and appears as follows:
{
"compilerOptions": {
"declaration": true,
"emitDecoratorMetadata": false,
"experimentalDecorators": false,
"module": "none",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": false,
"noImplicitAny": false,
"noImplicitReturns": false,
"removeComments": false,
"sourceMap": false,
"strictNullChecks": false,
"target": "es3"
},
"compileOnSave": true
}
Declaration file
Upon compiling TypeScript source code, there is an option to create a declaration file with the .d.ts extension. This file serves as an interface to the elements in the resulting JavaScript. When a file is labeled with the .d.ts extension, each top-level definition must be preceded by the declare keyword. This indicates that no actual code will be produced by TypeScript, thereby guaranteeing that the declared entity will be present during runtime. The declaration file also facilitates IntelliSense for JavaScript libraries, such as jQuery.
3. The TypeScript Language Services
The language service offers data that aids editors and various tools in enhancing assistance features, including automated refactoring and IntelliSense. It presents an extra layer surrounding the primary compiler pipeline. It accommodates several conventional editor functions such as code formatting and outlining, syntax highlighting, statement completion, and signature assistance, among others.