How to Set Up a TypeScript Project From Scratch

How to Set Up a TypeScript Project From Scratch

A comprehensive guide to architecting scalable, enterprise-grade TypeScript projects with strict type safety, modern toolchains, and CI automation.

Running tsc --init generates a standard tsconfig.json file full of commented-out directives. While this suffices for hobby projects or quick prototypes, enterprise software demands much more. Large-scale enterprise systems require strict type safety guarantees, deterministic builds, optimal developer experience (DX), instant feedback loops, and robust CI/CD integration.

In an enterprise environment, poor TypeScript setups lead to hidden bugs at runtime, degraded build performance, dependency hell, and subtle typing discrepancies across microservices or monorepo packages.

This guide details how to build a production-grade TypeScript project foundation from scratch using modern tooling: Node.js (LTS), pnpm, strict TypeScript directives, ESLint v9 (Flat Config), Prettier, Vitest, tsup, and Git hook automation.


1. Directory Structure and Project Initialization

Enterprise applications must decouple source logic, build outputs, configuration files, and quality gates cleanly. We will use pnpm for fast, deterministic, strict dependency management that prevents ghost dependencies (where code imports packages not explicitly declared in package.json).

Target Architecture

Here is the standardized directory blueprint:

my-enterprise-service/
├── .github/
│   └── workflows/
│       └── ci.yml
├── .husky/
│   ├── pre-commit
│   └── commit-msg
├── bin/
├── dist/
├── src/
│   ├── core/
│   │   └── logger.ts
│   ├── modules/
│   │   └── user/
│   │       ├── user.entity.ts
│   │       ├── user.service.ts
│   │       └── user.test.ts
│   ├── index.ts
│   └── types/
│       └── global.d.ts
├── .eslintrc.cjs / eslint.config.mjs
├── .gitignore
├── .prettierrc
├── commitlint.config.js
├── package.json
├── pnpm-lock.yaml
├── tsconfig.json
├── tsconfig.build.json
├── tsup.config.ts
└── vitest.config.ts

Initializing the Project

Initialize the Node.js project targeting ES Modules (ESM) natively by setting "type": "module" in your package.json.

mkdir my-enterprise-service
cd my-enterprise-service
pnpm init

Update your package.json with base metadata and module targets:

{
  "name": "@enterprise/user-service",
  "version": "1.0.0",
  "description": "High-throughput Enterprise User Service",
  "main": "./dist/index.js",
  "module": "./dist/index.mjs",
  "types": "./dist/index.d.ts",
  "type": "module",
  "scripts": {
    "build": "tsup",
    "typecheck": "tsc --noEmit",
    "lint": "eslint .",
    "lint:fix": "eslint . --fix",
    "format": "prettier --write \"src/**/*.ts\"",
    "test": "vitest run",
    "test:watch": "vitest",
    "prepare": "husky"
  },
  "engines": {
    "node": ">=20.0.0",
    "pnpm": ">=9.0.0"
  },
  "private": true
}

2. Architecting modern tsconfig.json Directives

Standard default configs are too permissive for enterprise software. We need to enforce strict type safety and explicit module semantics to prevent any contamination and unhandled undefined runtime crashes.

Instead of a single monolithic file, split your configuration into a base configuration (tsconfig.json) and a production build configuration (tsconfig.build.json).

Base Configuration (tsconfig.json)

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "compilerOptions": {
    /* Target & Runtime Language Syntax */
    "target": "ES2022",
    "lib": ["ES2022"],
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "useDefineForClassFields": true,

    /* Strict Type-Checking Options */
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,

    /* Additional Enterprise Safety Flags */
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitOverride": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,

    /* Emit Directives & Performance */
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "incremental": true,
    "tsBuildInfoFile": "./node_modules/.cache/tsconfig.tsbuildinfo",
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,

    /* Module Interop & ESM Explicit Rules */
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "verbatimModuleSyntax": true,
    "isolatedModules": true,

    /* Path Mapping */
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*", "tests/**/*", "tsup.config.ts", "vitest.config.ts"],
  "exclude": ["node_modules", "dist"]
}

Breakdown of Key Strictness Directives

  • noUncheckedIndexedAccess: Appends | undefined to record and array indexing lookups (map[key]). This forces developers to check for undefined before accessing properties, eliminating a vast category of standard runtime errors.
  • exactOptionalPropertyTypes: Enforces explicit semantic differentiation between { key?: string } (property can be missing) and { key: string | undefined } (property must exist, but value can be undefined).
  • verbatimModuleSyntax: Requires standard import type declarations for types, ensuring bundlers drop types predictably without complex side-effect analysis.
  • moduleResolution: "NodeNext": Enforces strict modern ESM Node.js runtime resolution rules, requiring explicit file extensions (.js) inside modern relative imports.

Production Build Configuration (tsconfig.build.json)

For production compilation, exclude test files, mock utilities, and local configurations:

{
  "extends": "./tsconfig.json",
  "exclude": [
    "node_modules",
    "dist",
    "src/**/*.test.ts",
    "src/**/*.spec.ts",
    "tests/**/*",
    "vitest.config.ts"
  ]
}

3. High-Performance Build Engine with tsup

Using the standard TypeScript compiler (tsc) directly to emit production JavaScript code can be slow in large codebases. Modern enterprise pipelines decouple type checking from code generation.

  • Use tsc --noEmit purely as a type validation step.
  • Use tsup (powered by esbuild) to handle lightning-fast bundler transpilation, generating dual ESM/CJS outputs and type definitions.

Install Build Dependencies

pnpm add -D tsup esbuild typescript

Create tsup.config.ts

import { defineConfig } from 'tsup';

export default defineConfig({
  entry: ['src/index.ts'],
  format: ['cjs', 'esm'],
  dts: true,
  sourcemap: true,
  clean: true,
  minify: true,
  splitting: true,
  treeshake: true,
  target: 'node20',
  outDir: 'dist',
  onSuccess: 'node dist/index.js',
});

4. Modern Code Quality Rules: ESLint v9 Flat Config & Prettier

ESLint v9 replaces the legacy .eslintrc architecture with the modern Flat Configuration (eslint.config.js). Combined with type-aware linting rules via @typescript-eslint, this setup catches deep anti-patterns before code hits code review.

Installing Quality Tools

pnpm add -D eslint @eslint/js typescript-eslint prettier eslint-config-prettier eslint-plugin-prettier

ESLint Flat Configuration (eslint.config.js)

Create an modern eslint.config.js file leveraging TypeScript type-checking context:

// @ts-check
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import prettierConfig from 'eslint-config-prettier';

export default tseslint.config(
  eslint.configs.recommended,
  ...tseslint.configs.strictTypeChecked,
  ...tseslint.configs.stylisticTypeChecked,
  {
    languageOptions: {
      parserOptions: {
        projectService: true,
        tsconfigRootDir: import.meta.dirname,
      },
    },
  },
  {
    rules: {
      '@typescript-eslint/no-explicit-any': 'error',
      '@typescript-eslint/explicit-function-return-type': 'error',
      '@typescript-eslint/no-floating-promises': 'error',
      '@typescript-eslint/await-thenable': 'error',
      '@typescript-eslint/no-misused-promises': 'error',
      '@typescript-eslint/consistent-type-imports': [
        'error',
        { prefer: 'type-imports', fixStyle: 'separate-type-imports' },
      ],
    },
  },
  {
    ignores: ['dist/', 'node_modules/', 'coverage/'],
  },
  prettierConfig
);

Prettier Configuration (.prettierrc)

{
  "singleQuote": true,
  "trailingComma": "all",
  "printWidth": 100,
  "tabWidth": 2,
  "semi": true,
  "bracketSpacing": true,
  "arrowParens": "always",
  "endOfLine": "lf"
}

5. Enterprise Testing Suite with Vitest

Vitest provides native ESM and TypeScript execution out of the box without requiring expensive transform pipelines like Babel or Jest transform hacks. It also inherently reads resolution mappings from tsconfig.json.

Install Vitest Stack

pnpm add -D vitest vite-tsconfig-paths

Vitest Configuration (vitest.config.ts)

import { defineConfig } from 'vitest/config';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
  plugins: [tsconfigPaths()],
  test: {
    globals: true,
    environment: 'node',
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html', 'lcov'],
      exclude: ['node_modules/', 'dist/', 'tsup.config.ts'],
      thresholds: {
        lines: 80,
        functions: 80,
        branches: 80,
        statements: 80,
      },
    },
  },
});

6. Path Aliases without Runtime Hacks

Relative paths like import { UserService } from '../../../../modules/user/user.service' degrade maintainability. Use path aliases (@/modules/...) mapped directly inside tsconfig.json.

Because we configured vite-tsconfig-paths for testing and tsup for compilation, alias mappings resolve automatically across runtime execution, type resolution, testing, and production compilation without needing brittle runtime rewrites like module-alias or tsconfig-paths.

Source Example (src/core/logger.ts)

export interface Logger {
  info(message: string, context?: Record<string, unknown>): void;
  error(message: string, error?: Error): void;
}

export class EnterpriseLogger implements Logger {
  public info(message: string, context?: Record<string, unknown>): void {
    console.log(JSON.stringify({ level: 'INFO', message, context, timestamp: new Date().toISOString() }));
  }

  public error(message: string, error?: Error): void {
    console.error(JSON.stringify({ level: 'ERROR', message, error: error?.stack, timestamp: new Date().toISOString() }));
  }
}

Source Example utilizing Path Alias (src/modules/user/user.service.ts)

import type { Logger } from '@/core/logger.js';

export interface User {
  id: string;
  email: string;
}

export class UserService {
  constructor(private readonly logger: Logger) {}

  public async getUserById(id: string): Promise<User> {
    this.logger.info('Fetching user', { userId: id });
    
    // Simulating database lookup
    if (id === '00000000-0000-0000-0000-000000000000') {
      throw new Error('User not found');
    }

    return {
      id,
      email: 'alex.engineer@enterprise.io',
    };
  }
}

7. Automated Developer Quality Gates (Git Hooks)

To ensure non-compliant code is never committed or pushed, set up Husky along with lint-staged and commitlint.

Install Git Hook Tools

pnpm add -D husky lint-staged @commitlint/cli @commitlint/config-conventional

Initialize Husky

pnpm exec husky init

Configure lint-staged in package.json

Add the following block to your package.json:

  "lint-staged": {
    "*.ts": [
      "eslint --fix",
      "prettier --write"
    ],
    "*.{json,md,yml}": [
      "prettier --write"
    ]
  }

Set up .husky/pre-commit

echo "pnpm exec lint-staged" > .husky/pre-commit
echo "pnpm typecheck" >> .husky/pre-commit

Configure Conventional Commit Formatting (commitlint.config.js)

Enforce clear git histories following standard enterprise specs:

export default { extends: ['@commitlint/config-conventional'] };

Add hook check:

echo "pnpm exec commitlint --edit \$1" > .husky/commit-msg

8. Enterprise Continuous Integration (CI) Automation

Automate build verification in CI to act as the final quality gate before pull requests merge into main branches.

GitHub Actions Workflow (.github/workflows/ci.yml)

name: Continuous Integration

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  verify:
    name: Build, Lint & Test
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Source Code
        uses: actions/checkout@v4

      - name: Install pnpm
        uses: pnpm/action-setup@v3
        with:
          version: 9

      - name: Setup Node.js Environment
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - name: Install Dependencies
        run: pnpm install --frozen-lockfile

      - name: Execute Type Check
        run: pnpm typecheck

      - name: Run Linter
        run: pnpm lint

      - name: Run Unit Tests with Coverage
        run: pnpm test

      - name: Compile Production Artifacts
        run: pnpm build

Architecture Checklist Summary

Before deploying this template to production software teams, run through this verification matrix:

Architectural Metric Enterprise Standard Target Verification Tool / Flag
Type Rigor Zero implicit any, Strict Optional Checking tsconfig.json (strict, noUncheckedIndexedAccess)
Module System Pure Native ES Modules (ESM) "type": "module", "moduleResolution": "NodeNext"
Linting Strategy AST-based static type analysis ESLint v9 Flat Config with @typescript-eslint
Build Transpilation Modern decoupled builds Fast bundler (tsup) with static validation (tsc --noEmit)
Testing Standards Isolated execution & 80%+ threshold Vitest with Coverage engine
Git Governance Enforced static linting and conventional commits Husky + lint-staged + commitlint

Conclusion

A naive TypeScript configuration provides type safety on paper, but often fails under enterprise demands. Building a production-grade TypeScript project requires:

  1. Setting up strict compilation directives (noUncheckedIndexedAccess, verbatimModuleSyntax).
  2. Decoupling type checking (tsc) from bundling (tsup).
  3. Configuring AST-level linting with modern ESLint v9 Flat Config.
  4. Enforcing strict automated checks at the git-hook and CI pipeline levels.

By building on top of this architectural blueprint, your engineering organization gets deterministic builds, robust runtime guarantees, fast compile cycles, and an exceptional baseline developer experience that scales cleanly across teams and repos.