Computer scienceProgramming languagesTypeScriptIntroduction to TypeScript

Compiling TypeScript

5 minutes read

TypeScript is a statically typed superset of JavaScript that adds optional types, classes, and modules to the language, while also supporting the latest JavaScript features. However, browsers and Node.js (a popular JavaScript runtime) don't understand TypeScript directly. This is why TypeScript needs to be "compiled" (or, to be precise, transpiled) into JavaScript before it can be executed. In this topic, you will get a general overview of the compilation process in TypeScript and learn how to compile a TypeScript file.

TypeScript compilation process

  1. Type-checking. TypeScript uses static typing which allows you to define the type of variables, function parameters, returned values, and object properties. During the compilation process, the TypeScript compiler (tsc) will perform a type-check, verifying that the types specified in your code are being used correctly. If there are any type errors, the compiler will throw an error.

  2. Transpilation. After the type-checking process, the TypeScript compiler will then convert (or "transpile") your TypeScript code into JavaScript. This process includes transforming TypeScript-specific features, like interfaces and type annotations, into JavaScript code that can be executed in a browser or Node.js environment. The TypeScript compiler can output different versions of JavaScript (ES5, ES6, etc.) depending on your configuration settings.

How to compile a TypeScript file

To compile TypeScript files, you'll need to have both Node.js and the TypeScript package installed on your machine. Let's look at each step:

  1. Install Node.js. Node.js is a JavaScript runtime that allows you to run JavaScript code on your machine. You can download it from the official website. After downloading, follow the prompts to install it. You can also check if you have Node installed on your machine on a terminal or command prompt with this:

    node -v
  2. Install TypeScript. Once Node.js is installed, you can install TypeScript globally on your machine using npm (Node Package Manager), which comes with Node.js. Open a terminal or command prompt and type the following command:

    npm install -g typescript

    The -g flag means that TypeScript will be installed globally, and you can use it from anywhere on your machine. You need to use sudo or have admin permissions to use this flag.

  3. Write TypeScript code. Create a new .ts file and write some TypeScript code. For example, create a file called hello.ts with the following code:

    function hello(name: string) {
        console.log('Hello, ' + name + '!');
    }
    
    hello('TypeScript');

    Above script shown on the WebStorm IDE with the file manager on the left. The file is hello.ts

  4. Compile TypeScript code. Now you can use the TypeScript compiler (tsc) to compile your TypeScript code into JavaScript. In the terminal, navigate to the directory containing your hello.ts file and type the following command:

    tsc hello.ts

    If the above command doesn't work, try this one:

    npx tsc hello.ts

    This will create a new file called hello.js in the same directory, which contains the compiled JavaScript code.
    Result of  the above command on the WebStorm IDE with the file manager on the left. The command creates the file hello.js

  5. Run the JavaScript code. You can now run the compiled JavaScript code using Node.js:

    node hello.js

    This will print "Hello, TypeScript!" to the console.

TSConfig.json

The TypeScript compiler is controlled by a configuration file named tsconfig.json. This file allows you to specify various options for the compiler, such as the JavaScript version to output (target), whether to include source maps (sourceMap), which files to include in the compilation (include), and many other options.

Source maps are files that provide mapping between the original source code (e.g. TypeScript) and the corresponding transpiled code (e.g. JavaScript). They allow developers to debug and trace issues in the original source code, even when working with compiled code. Source maps are generated by the TypeScript compiler when the sourceMap option is enabled in the tsconfig.json file. They contain information about the original file structure, line numbers, and variable names. This mapping information is stored in a separate file with the extension .map (e.g., main.js.map).

To generate a tsconfig.json file with default settings, use this command:

tsc --init

Here's a basic example of a tsconfig.json file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "outDir": "./dist"
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

Let's break down what each of these properties does:

  • compilerOptions: this property is where you specify various options that the compiler will use.

    • target: specifies the output language level. In this case, it's "es5", but it could be "es6", "esnext", etc.
    • module: specifies the module system to be used. "commonjs" is used for Node.js.
    • strict: enables a wide range of type-checking behavior that results in more type-safe programs.
    • outDir: the output directory for the JavaScript files that the TypeScript compiler will create.
  • include: an array of glob patterns that match the files you want to include in your compilation.

  • exclude: an array of glob patterns that match the files you want to exclude from your compilation.

There are many other options that you can use in your tsconfig.json file, such as lib (which allows you to specify library files to be included in the compilation), and jsx (which specifies JSX code generation). For more detailed information about the various options available in a tsconfig.json file, you can refer to the official TypeScript documentation.

Conclusion

TypeScript is a tool to make JavaScript development safer and more efficient, but the resulting application that runs in the end is pure JavaScript. To compile TypeScript, you need to have Node.js and TypeScript package installed. After that, you can compile TypeScript and run the generated JavaScript file. You may also need to use the tsconfig.json file to configure the TypeScript compiler.

11 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo