Frontend

TypeScript Setup & Deployment Guide

Add static types to JavaScript – install the compiler, configure tsconfig, build and run typed Node.js and React code in production.

Updated Official documentation ↗

1. Introduction & use cases

TypeScript is JavaScript with static types, developed by Microsoft. You write .ts/.tsx files with type annotations; the compiler (tsc) checks them and outputs plain JavaScript that runs anywhere JavaScript runs.

Types catch mistakes – a misspelt property, a missing argument, undefined where an object was expected – before the code runs, and give editors excellent autocomplete and safe refactoring. Types disappear at runtime, so deployment means shipping the compiled JavaScript (or letting a bundler like Vite or Next.js handle it).

Where it is used

  • Large front-end apps with React, Angular, Vue or Next.js
  • Node.js back-ends (Express, NestJS) and serverless functions
  • Libraries that publish type definitions for their users
  • Teams that want safer refactoring and self-documenting code

2. Prerequisites

You needVersion / notes
Node.jsCurrent LTS release (check with node -v). Download from nodejs.org or install with nvm.
EditorVS Code has built-in TypeScript support
BasicsModern JavaScript (ES modules, classes, async/await)

3. Local setup

  1. 1Create a project and install TypeScript

    Install TypeScript per project (not globally) so everyone uses the same version.

    BASH
    mkdir ts-demo && cd ts-demo
    npm init -y
    npm install --save-dev typescript @types/node tsx
  2. 2Generate tsconfig.json

    tsc --init creates a commented config. Then adjust the main options shown below.

    BASH
    npx tsc --init
  3. 3Use a sensible configuration

    strict turns on all important checks. For a Node.js project compile src/ to dist/.

    tsconfig.json
    {
      "compilerOptions": {
        "target": "ES2022",
        "module": "NodeNext",
        "moduleResolution": "NodeNext",
        "rootDir": "src",
        "outDir": "dist",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "sourceMap": true
      },
      "include": ["src"]
    }
  4. 4Add scripts

    Use tsx to run TypeScript directly while developing, and tsc to type-check and build.

    package.json (scripts)
    "scripts": {
      "dev": "tsx watch src/index.ts",
      "typecheck": "tsc --noEmit",
      "build": "tsc",
      "start": "node dist/index.js"
    }

4. Create & run a project

  1. 1Write typed code

    Interfaces describe object shapes; functions declare parameter and return types.

    src/index.ts
    export interface User {
      id: number;
      name: string;
      email?: string; // optional
    }
    
    export function greet(user: User): string {
      return `Hello, ${user.name}!`;
    }
    
    const users: User[] = [{ id: 1, name: 'Asha' }, { id: 2, name: 'Ravi', email: 'ravi@example.com' }];
    users.forEach((u) => console.log(greet(u)));
  2. 2Run it in watch mode

    tsx runs the file and restarts on changes (it does not type-check – run npm run typecheck for that).

    BASH
    npm run dev
  3. 3See a type error

    Try greet({ id: 3 }) – the editor and tsc report that name is missing, before you ever run the code.

    OUTPUT
    npm run typecheck
    # src/index.ts:14:7 - error TS2345: Argument of type '{ id: number; }'
    #   is not assignable to parameter of type 'User'.
  4. 4Build JavaScript

    tsc writes JavaScript and source maps to dist/.

    BASH
    npm run build
    npm start

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

TypeScript has no environment variables of its own. For typed configuration, validate process.env once at startup (for example with zod) and export a typed config object. Node.js 20.6+ can load a file with node --env-file=.env.

.env
NODE_ENV=development
PORT=3000
API_KEY=replace-me

Key dependencies

Package / toolUsed for
typescriptThe compiler tsc and language service
tsxRun .ts files directly in development (fast, no type-check)
@types/nodeType definitions for Node.js APIs
@types/* packagesTypes for libraries that do not ship their own
typescript-eslintLint rules that understand types
zod (optional)Runtime validation that also produces TypeScript types

Folder structure

project structure
ts-demo/
├── src/
│   ├── index.ts
│   └── types/          # shared interfaces
├── dist/               # compiled JS (git-ignored)
├── package.json
└── tsconfig.json

Essential commands

CommandWhat it does
npx tsc --initCreate tsconfig.json
npx tsc --noEmitType-check only (great for CI)
npx tscCompile to outDir
npx tsc --watchRecompile on every change
npx tsx file.tsRun a TypeScript file directly

6. Production deployment

Browsers and Node.js run JavaScript, so production uses the compiled output. Front-end frameworks (Vite, Next.js) compile TypeScript during their build. For a Node.js service, run tsc in CI or on the server and start node dist/index.js. (Recent Node.js versions can also strip simple type annotations themselves, but compiling keeps type errors out of production.)

Server & hosting requirements

RequirementRecommendation
Build stepNode.js LTS + npm ci && npm run build (CI recommended)
RuntimeNode.js LTS on the server (only dist/ and production dependencies are needed)
Process managerPM2 or systemd
WebNginx reverse proxy + SSL if it serves HTTP

Deployment steps

  1. 1Type-check and build in CI

    Fail the pipeline on type errors.

    BASH
    npm ci
    npx tsc --noEmit
    npm run build
  2. 2Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  3. 3Install Node.js on the server

    Install the current LTS release with nvm (or the NodeSource packages). Use the same major version as on your computer.

    BASH
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    source ~/.bashrc
    nvm install --lts
    node -v && npm -v
  4. 4Get the code and build it

    Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with npm ci and build.

    BASH
    git clone https://github.com/you/your-app.git /var/www/ts-app
    cd /var/www/ts-app
    npm ci
    npm run build
    npm prune --omit=dev   # keep only runtime dependencies
  5. 5Keep the app running with PM2

    PM2 restarts the app if it crashes and starts it again after a server reboot. pm2 startup prints one command – run it with sudo, then pm2 save.

    BASH
    sudo npm install -g pm2
    pm2 start dist/index.js --name ts-app
    pm2 startup          # run the command it prints
    pm2 save
    pm2 logs ts-app        # live logs
    pm2 restart ts-app     # after each deploy
  6. 6Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:3000. Replace example.com with your domain.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
    
        location / {
            proxy_pass http://127.0.0.1:3000;
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }
  7. 7Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  8. 8Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  9. 9Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ npm run dev> tsx watch src/index.tsHello, Asha!Hello, Ravi!$ npm run build && npm start> tsc> node dist/index.jsHello, Asha!Hello, Ravi!
Figure 1: terminal output of the sample TypeScript project (section 4).
1Write .ts files2tsc --noEmit in CI3tsc → dist/*.js4node dist/index.js5Nginx + HTTPS
Figure 2: production deployment flow (section 6).
ts-demo/├── src/│ ├── index.ts│ └── types/ # shared interfaces├── dist/ # compiled JS (git-ignored)├── package.json└── tsconfig.json
Figure 3: project folder structure (section 5).

8. Common errors & solutions

TS2307: Cannot find module 'x' or its corresponding type declarations

Install the package and its types (npm i -D @types/x) if it does not ship its own, and check moduleResolution.

ERR_UNKNOWN_FILE_EXTENSION ".ts" when running node src/index.ts

Run TypeScript with tsx, or compile first and run node dist/index.js.

Relative imports fail after compiling with module: NodeNext

ES module output needs file extensions in imports: write import { x } from './util.js' (yes, .js) in your .ts file.

TS2532: Object is possibly 'undefined'

Handle the empty case (if (!user) return;), use optional chaining user?.name, or a default value. Avoid silencing it with ! unless you are sure.

Types are fine but the app crashes on bad API data

Types are compile-time only. Validate external data (API responses, env vars, user input) at runtime with zod or similar.

Best practices

  • Turn on strict from day one – adding it later is much harder.
  • Avoid any; prefer unknown and narrow it.
  • Run tsc --noEmit in CI on every pull request.
  • Keep shared types in one place and generate API types from OpenAPI/GraphQL schemas where possible.
  • Ship only dist/ and production dependencies to servers.