> ## Documentation Index
> Fetch the complete documentation index at: https://sonamu.cartanova.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# tsconfig.json

> Configuring TypeScript

Sonamu projects are written in TypeScript, with API and Web each having independent `tsconfig.json` files. They use configurations optimized for their respective environments.

## Project Structure

<FileTree>
  * my-project/ - api/ - tsconfig.json # API server configuration - tsconfig.schemas.json # Schema
    generation - tsconfig.types.json # Type generation - web/ - tsconfig.json # React app
    configuration - tsconfig.node.json # Vite configuration
</FileTree>

<Info>API and Web are independent TypeScript projects. Their configurations are separate.</Info>

## API Server Configuration

### Base tsconfig.json

```json title="api/tsconfig.json" theme={null}
{
  "compilerOptions": {
    /* Basic Options */
    "target": "esnext",
    "module": "esnext",
    "outDir": "dist",
    "sourceMap": true,
    "lib": ["esnext", "dom"],

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

    /* Additional Checks */
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "useUnknownInCatchVariables": true,

    /* Module Resolution Options */
    "moduleResolution": "bundler",
    "esModuleInterop": true,

    /* Experimental Options */
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,

    /* Advanced Options */
    "forceConsistentCasingInFileNames": true,
    "noErrorTruncation": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "noUncheckedIndexedAccess": true
  },
  "include": ["src/**/*.ts", "src/**/*.json"],
  "exclude": [
    "node_modules",
    "dist/*",
    "public",
    // "src/**/*.test.ts",  // Test files also type-checked, so commented out
    "**/__mocks__/**",
    "vite.config.ts"
  ]
}
```

### Key Options Explained

<Tabs>
  <Tab title="Module Settings" icon="cube">
    ```json theme={null}
    {
      "target": "esnext",           // Use latest ECMAScript syntax
      "module": "esnext",            // Output ES modules
      "moduleResolution": "bundler"  // Compatible with Vite/esbuild
    }
    ```

    **moduleResolution: "bundler"**

    * Uses bundler mode instead of Node.js's `node` mode
    * Matches how Vite and esbuild resolve modules
    * Supports `package.json`'s `exports` field

    <Warning>
      Using `moduleResolution: "node"` may conflict with Vite.
    </Warning>
  </Tab>

  <Tab title="Decorators" icon="sparkles">
    ```json theme={null}
    {
      "experimentalDecorators": true,
      "emitDecoratorMetadata": true
    }
    ```

    **Required in Sonamu API**

    * Use `@api` decorator for API methods
    * Use `@transactional` decorator for transactions
    * Use `@upload` decorator for file uploads

    **Usage Example:**

    ```typescript theme={null}
    import { BaseModelClass, api, transactional } from "sonamu";

    class UserModelClass extends BaseModelClass<
      UserSubsetKey,
      UserSubsetMapping,
      UserSubsetQueries
    > {
      @api({ httpMethod: "GET" })
      async findById(subset: UserSubsetKey, id: number) {
        const rdb = this.getPuri("r");
        return rdb.table("users").where("id", id).first();
      }

      @api({ httpMethod: "POST" })
      @transactional()
      async save(data: UserSaveParams) {
        const wdb = this.getDB("w");
        return this.upsert(wdb, data);
      }
    }

    export const UserModel = new UserModelClass();
    ```

    <Info>
      Entities are defined in `entity.json` files and do not use TypeScript decorators. See [Defining Entities](/en/core-concepts/entity/defining-entities) for details.
    </Info>
  </Tab>

  <Tab title="Strict Mode" icon="shield-check">
    ```json theme={null}
    {
      "strict": true,
      "noImplicitAny": true,
      "strictNullChecks": true,
      "strictFunctionTypes": true,
      "strictBindCallApply": true,
      "strictPropertyInitialization": true,
      "noImplicitThis": true,
      "alwaysStrict": true
    }
    ```

    Sonamu **enables all strict options**.

    * Maximize type safety
    * Prevent runtime errors in advance
    * Improve code quality

    See [Type Checking](/en/configuration/typescript/type-checking) for details.
  </Tab>

  <Tab title="Additional Checks" icon="list-check">
    ```json theme={null}
    {
      "noUnusedLocals": true,
      "noUnusedParameters": true,
      "noImplicitReturns": true,
      "noFallthroughCasesInSwitch": true,
      "useUnknownInCatchVariables": true,
      "noUncheckedIndexedAccess": true
    }
    ```

    **Code Quality Improvement Options:**

    * `noUnusedLocals`: Warn about unused variables
    * `noUnusedParameters`: Warn about unused parameters
    * `noImplicitReturns`: Require return in all paths
    * `noUncheckedIndexedAccess`: Check for undefined when accessing arrays/objects
  </Tab>
</Tabs>

### Extended Configuration Files

Sonamu API uses additional tsconfig files for code generation.

<Accordion title="tsconfig.schemas.json - Schema Generation" icon="database">
  ```json title="api/tsconfig.schemas.json" theme={null}
  {
    "extends": "./tsconfig.json",
    "include": ["src/sonamu.generated.ts"],
    "exclude": ["src/**/*.types.ts"]
  }
  ```

  **Purpose:**

  * Generate `sonamu.generated.ts` file
  * Generate Entity schema types
  * Convert DB schema → TypeScript types

  **When Used:**

  ```bash theme={null}
  # Automatically used by Sonamu
  pnpm sonamu entity:load
  ```
</Accordion>

<Accordion title="tsconfig.types.json - Type Generation" icon="code">
  ```json title="api/tsconfig.types.json" theme={null}
  {
    "extends": "./tsconfig.json",
    "include": ["src/**/*.types.ts"],
    "references": [{ "path": "./tsconfig.schemas.json" }]
  }
  ```

  **Purpose:**

  * Generate API response types
  * Define Request/Response types
  * Share types with frontend

  **When Used:**

  ```bash theme={null}
  # Sync types to Web
  pnpm sonamu sync:types
  ```
</Accordion>

## Web (React) Configuration

```json title="web/tsconfig.json" theme={null}
{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["src", "src/routeTree.gen.ts"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
```

### Differences from API

| Option             | API       | Web         | Reason                     |
| ------------------ | --------- | ----------- | -------------------------- |
| `moduleResolution` | `bundler` | `Bundler`   | Vite uses bundler mode     |
| `jsx`              | -         | `react-jsx` | React 17+ JSX Transform    |
| `noEmit`           | `false`   | `true`      | Vite handles build         |
| `isolatedModules`  | -         | `true`      | Required by Vite's esbuild |
| `paths`            | -         | `@/*`       | Absolute path imports      |

<Info>
  API uses `moduleResolution: "bundler"` (lowercase), Web uses `moduleResolution: "Bundler"`
  (uppercase). Both make Vite resolve modules in bundler mode.
</Info>

### Path Mapping

```json theme={null}
{
  "paths": {
    "@/*": ["./src/*"]
  }
}
```

You can import with absolute paths:

```typescript theme={null}
// ❌ Relative path
import { Button } from "../../../components/Button";

// ✅ Absolute path
import { Button } from "@/components/Button";
```

See [Path Mapping](/en/configuration/typescript/path-mappings) for details.

## Running Type Checks

<Tabs>
  <Tab title="API" icon="server">
    ```bash theme={null}
    cd api

    # Type check only
    pnpm tsc --noEmit

    # Watch mode
    pnpm tsc --noEmit --watch
    ```
  </Tab>

  <Tab title="Web" icon="browser">
    ```bash theme={null}
    cd web

    # Type check only
    pnpm tsc --noEmit

    # Watch mode
    pnpm tsc --noEmit --watch
    ```
  </Tab>

  <Tab title="All" icon="folder">
    ```bash theme={null}
    # From project root
    pnpm -r tsc --noEmit

    # Check API and Web simultaneously
    ```
  </Tab>
</Tabs>

<Tip>During development, `--watch` mode is recommended for real-time type checking.</Tip>

## Common Troubleshooting

<Accordion title="Cannot Find Module" icon="magnifying-glass">
  **Symptoms:**

  ```
  Cannot find module 'sonamu' or its corresponding type declarations.
  ```

  **Cause:**

  * `node_modules` not installed
  * Incorrect import path

  **Solution:**

  ```bash theme={null}
  # Reinstall dependencies
  pnpm install

  # Check type definitions
  ls node_modules/sonamu/dist/*.d.ts
  ```
</Accordion>

<Accordion title="Decorator Error" icon="sparkles">
  **Symptoms:**

  ```
  Experimental support for decorators is a feature that is subject to change
  ```

  **Cause:**

  * `experimentalDecorators` is disabled

  **Solution:**

  ```json theme={null}
  {
    "compilerOptions": {
      "experimentalDecorators": true,
      "emitDecoratorMetadata": true
    }
  }
  ```
</Accordion>

<Accordion title="JSX Error (Web)" icon="react">
  **Symptoms:**

  ```
  Cannot use JSX unless the '--jsx' flag is provided.
  ```

  **Cause:**

  * `jsx` option not configured

  **Solution:**

  ```json theme={null}
  {
    "compilerOptions": {
      "jsx": "react-jsx"
    }
  }
  ```

  **Required for React 17+**
</Accordion>

<Accordion title="Path Mapping Not Working" icon="route">
  **Symptoms:**

  ```
  Cannot find module '@/components/Button'
  ```

  **Cause:**

  * `paths` configuration missing
  * `baseUrl` configuration needed

  **Solution:**

  ```json theme={null}
  {
    "compilerOptions": {
      "baseUrl": ".",
      "paths": {
        "@/*": ["./src/*"]
      }
    }
  }
  ```

  **Vite configuration also needed:**

  ```typescript title="vite.config.ts" theme={null}
  import path from "path";

  export default {
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src"),
      },
    },
  };
  ```
</Accordion>

## Customization

### Additional Library Types

```json theme={null}
{
  "compilerOptions": {
    "lib": ["esnext", "dom", "dom.iterable", "webworker"]
  }
}
```

### Stricter Checks

```json theme={null}
{
  "compilerOptions": {
    "noPropertyAccessFromIndexSignature": true,
    "exactOptionalPropertyTypes": true,
    "noUncheckedIndexedAccess": true
  }
}
```

<Warning>These options may cause compatibility issues with existing code.</Warning>

### include/exclude Patterns

```json theme={null}
{
  "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.json"],
  "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts", "**/__mocks__/**"]
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Type Checking" icon="shield-check" href="/en/configuration/typescript/type-checking">
    Learn about Strict mode and type check options
  </Card>

  <Card title="Path Mapping" icon="route" href="/en/configuration/typescript/path-mappings">
    Configure absolute path imports
  </Card>

  <Card title="Defining Entities" icon="database" href="/en/core-concepts/entity/defining-entities">
    Define Entities
  </Card>

  <Card title="API Types" icon="code" href="/en/core-concepts/type-system/entity-types">
    Define API request/response types
  </Card>
</CardGroup>
