A Comprehensive Guide to Setting Up and Configuring TypeScript for Your Projects

Installing TypeScript

To install TypeScript for your project, use one of the following package managers:

# Using NPM
npm install typescript --save-dev

# Using PNPM
pnpm add -D typescript

# Using Yarn
yarn add --dev typescript

Installing Type Definitions for React (Optional)

If you are working on a React project, you need to install the following packages:

# Using NPM
npm install @types/react @types/react-dom --save-dev

# Using PNPM
pnpm add -D @types/react @types/react-dom

# Using Yarn
yarn add --dev @types/react @types/react-dom

Setting up the tsconfig.json Configuration File

After installing TypeScript, run the following command to generate a tsconfig.json file in your project's root directory:

# Choose your package manager
npm tsc --init

This will generate a tsconfig.json file in your project directory:

├── src
│   └── ...
├── package.json
├── tsconfig.json
├── README.md
├── pnpm-lock.yaml
└── pnpm-workspace.yaml

Modifying Compiler Options in tsconfig.json

Open the tsconfig.json file and set the following properties:

/* tsconfig.json */

{
  "compilerOptions": {
    /* Language and Environment */
    "target": "ESNext",
    "lib": [
      "ESNext",
      "DOM"
    ],
    "jsx": "react",

    /* Modules */
    "module": "ESNext",
    "moduleResolution": "Node",
    "baseUrl": ".",
    "resolveJsonModule": true,

    /* Emit */
    "declaration": true,
    "noEmit": true,

    /* Interop Constraints */
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,

    /* Type Checking */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowUnusedLabels": false,
    "allowUnreachableCode": false,

    /* Completeness */
    "skipLibCheck": true
  }
}