Lesson 6 of 60 – TypeScript Compiler
10%

TypeScript Compiler

The TypeScript Compiler is a tool that checks TypeScript code and transforms it into JavaScript. The compiler is commonly called tsc.

Note: Browsers and JavaScript runtimes execute JavaScript. TypeScript code is normally checked and transformed into JavaScript before it is executed.

1. What is the TypeScript Compiler?

The TypeScript compiler is a program that processes TypeScript source code and produces JavaScript output.

TypeScript
     ↓
TypeScript Compiler
     ↓
JavaScript

The compiler also performs type checking based on the project's configuration.

2. What is tsc?

tsc is the command-line TypeScript compiler. It is used to compile TypeScript programs.

tsc app.ts

The command tells the TypeScript compiler to process app.ts.

3. Check the TypeScript Compiler Version

You can check whether the TypeScript compiler is available by running:

tsc --version

If TypeScript is installed globally and available in the system path, this command displays its version.

For a locally installed compiler, you can use:

npx tsc --version

4. Compile a TypeScript File

Suppose you have a file named app.ts. You can compile it using:

npx tsc app.ts

The compiler processes the TypeScript file and can generate app.js.

5. Simple TypeScript File

Create a file named app.ts:

let message: string = "Hello TypeScript";

console.log(message);

This program contains a type annotation for the message variable.

6. Compile the File

Open the terminal in the project folder and run:

npx tsc app.ts

If compilation succeeds, JavaScript output can be generated.

7. Generated JavaScript

After compilation, the TypeScript code is transformed into JavaScript. For a simple example, the generated file can look like:

let message = "Hello TypeScript";

console.log(message);

The type annotation is not needed in the generated JavaScript.

8. TypeScript Compiler Checks Types

The compiler can detect type-related problems.

let age: number = 20;

age = "Hello";

The compiler reports an error because age is declared as a number.

9. Compiler and Type Annotations

Type annotations provide information to the compiler.

let studentName: string = "Amit";
let marks: number = 85;
let passed: boolean = true;

The compiler can use this information when checking the code.

10. Compile Multiple Files

You can compile multiple TypeScript files together.

npx tsc app.ts student.ts

The compiler processes the specified files.

11. Compile the Whole Project

For a project using tsconfig.json, you can compile the project by running:

npx tsc

The compiler reads the project configuration and processes the files according to that configuration.

12. What is tsconfig.json?

tsconfig.json is the TypeScript configuration file. It allows you to define how the TypeScript compiler should process the project.

A configuration file can be created using:

npx tsc --init

13. Basic tsconfig.json

A simple configuration can specify the JavaScript target. For example:

{
    "compilerOptions": {
        "target": "ES2020"
    }
}

The exact configuration used by a project depends on its requirements.

14. Target Option

The target compiler option specifies the JavaScript language level that the compiler should generate.

{
    "compilerOptions": {
        "target": "ES2020"
    }
}

The target should be selected according to the environments supported by the application.

15. Module Option

The module option controls the module system used by the generated JavaScript.

{
    "compilerOptions": {
        "module": "commonjs"
    }
}

Modern projects may use different module systems depending on the toolchain.

16. Strict Type Checking

TypeScript provides strict checking options that can help identify potential problems in code.

{
    "compilerOptions": {
        "strict": true
    }
}

Strict checking can provide stronger compile-time checks.

17. Output Directory

The outDir option can specify where compiled JavaScript files should be placed.

{
    "compilerOptions": {
        "outDir": "./dist"
    }
}

This can keep generated files separate from the source files.

18. Root Directory

The rootDir option can specify the directory containing the TypeScript source files.

{
    "compilerOptions": {
        "rootDir": "./src"
    }
}

This is useful when organizing larger projects.

19. Source and Output Folders

A project can keep TypeScript source code in one folder and generated JavaScript in another folder.

project/
│
├── src/
│   └── app.ts
│
├── dist/
│   └── app.js
│
└── tsconfig.json

This keeps source and generated files organized.

20. NoEmit Option

The noEmit option can be used when you want TypeScript to check the code without generating JavaScript output.

{
    "compilerOptions": {
        "noEmit": true
    }
}

This can be useful in workflows where another tool handles code generation.

21. Watch Mode

The TypeScript compiler can watch files for changes and recompile when source files are modified.

npx tsc --watch

This can be useful during development because the compiler can respond to changes without manually running the compile command each time.

22. Compiler Errors

When TypeScript finds an error, the compiler displays information about the problem.

let age: number = 20;

age = "twenty";

The compiler can identify the incompatible assignment and show information that helps you locate the problem.

23. Compiler and Functions

The compiler also checks function parameters and return types.

function add(
    a: number,
    b: number
): number {
    return a + b;
}

An incorrect function call can be detected during type checking.

add(10, "20");

24. Compiler and Interfaces

The compiler can also check whether objects follow an interface.

interface Student {
    name: string;
    age: number;
}

let student: Student = {
    name: "Rahul",
    age: 20
};

The object is checked against the structure defined by the interface.

25. Compile TypeScript with a Specific Output

Compiler options can be passed directly on the command line. For example:

npx tsc app.ts --target ES2020

This tells the compiler to generate JavaScript targeting the specified JavaScript language level.

26. TypeScript Compiler Workflow

Write TypeScript
       ↓
Run TypeScript Compiler
       ↓
Check Types
       ↓
Generate JavaScript
       ↓
Run JavaScript

This is the basic idea behind TypeScript compilation.

27. TypeScript Compiler in React Projects

React projects that use TypeScript normally include TypeScript configuration and tooling as part of the project setup.

Components can be written using .tsx files.

App.tsx
Home.tsx
Profile.tsx

The project's build tool handles the transformation required to run the application.

28. TypeScript Compiler in React Native

React Native applications can also use TypeScript. TypeScript files containing JSX commonly use the .tsx extension.

import { View, Text } from "react-native";

const App = () => {
    return (
        <View>
            <Text>Hello React Native</Text>
        </View>
    );
};

The React Native project tooling processes the TypeScript code as part of the application build process.

29. Complete Compiler Example

Create a project:

mkdir ts-demo
cd ts-demo

npm init -y
npm install --save-dev typescript

npx tsc --init

Create app.ts:

interface Student {
    name: string;
    marks: number;
}

const student: Student = {
    name: "Amit",
    marks: 90
};

console.log(student.name);
console.log(student.marks);

Compile the project:

npx tsc

30. Important Compiler Commands

Command Purpose
tsc --version Check global TypeScript compiler version
npx tsc --version Check the project TypeScript compiler version
npx tsc app.ts Compile a TypeScript file
npx tsc Compile a configured project
npx tsc --init Create tsconfig.json
npx tsc --watch Watch files and recompile changes
Remember: The TypeScript compiler is responsible for checking TypeScript code and transforming it according to the project's compiler configuration. The command-line compiler is called tsc.

📌 Key Points

  • tsc is the TypeScript compiler command.
  • The compiler checks TypeScript code.
  • The compiler can detect many type-related errors.
  • TypeScript can be compiled into JavaScript.
  • npx tsc app.ts can compile a specific file.
  • npx tsc can compile a configured project.
  • tsconfig.json contains compiler configuration.
  • target controls the JavaScript language level being generated.
  • outDir can specify the output directory.
  • npx tsc --watch enables compiler watch mode.
  • React and React Native projects can use TypeScript.

🧠 Quick Quiz

Question: What is the main purpose of the TypeScript compiler?