Typescript Foundations / Introduction to Typescript

The Typescript Compiler

The TypeScript Compiler (tsc) is the tool that:

πŸ‘‰ Converts TypeScript code (.ts / .tsx files) into plain JavaScript (.js)

πŸ‘‰ Checks your code for type errors before compiling

βœ… The output JavaScript can run anywhere JavaScript runs β€” browsers, Node.js, etc.

βœ… The compiler makes sure your code is type-safe (according to the types you wrote or inferred).


πŸ”‘ Main responsibilities of tsc

  • Transpile TypeScript (and modern JS features) into compatible JavaScript

  • Check types and report type errors

  • Handle advanced features like decorators, namespaces, and modules

  • Support config-driven builds via tsconfig.json


πŸ“ Basic tsc commands

1️⃣ Compile a single file:

tsc index.ts

This creates index.js in the same folder.


2️⃣ Compile all files in your project (when tsconfig.json is present):

tsc

or

npm run build

(if you defined a build script)


3️⃣ Watch files (automatic recompile on save):

tsc --watch

πŸ‘‰ This is useful during development for faster feedback.


βš™οΈ tsconfig.json and Compiler Options

You can control how tsc works using a tsconfig.json file.

tsc --init

creates a default config.

Common options you might see:

{
  "compilerOptions": {
    "target": "es6",           // JS version output
    "module": "commonjs",      // Module system (commonjs, es6, etc.)
    "outDir": "./dist",        // Output directory for JS files
    "strict": true,            // Enable all strict type checks
    "esModuleInterop": true,   // Allow default imports from commonjs
    "sourceMap": true          // Generate source maps for debugging
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

πŸ‘‰ This way, tsc knows how to process your files and where to put the output.


🌟 Type checking

Even if you don’t want to generate JavaScript, you can run:

tsc --noEmit

βœ… This checks types but doesn’t produce .js files. Useful for CI and code quality checks!


🎁 Bonus Tips

  • You can use tsc with build tools (Webpack, Vite) to integrate into modern workflows.

  • Tools like Babel can be used alongside tsc to handle transpiling + polyfilling.

  • TypeScript compiler API allows you to build custom tooling (advanced).


πŸš€ Example workflow

tsc --init               // Create config
tsc                      // Compile all TypeScript files
tsc --watch              // Recompile automatically on file change
tsc --noEmit             // Only check types

πŸ’‘ Summary

Feature

Purpose

tsc

Transpile TypeScript to JavaScript

tsc --watch

Live compile on file changes

tsconfig.json

Control compiler settings

tsc --noEmit

Type check only, no JS output