TypeScript Guide

Learn how to leverage TypeScript in your Xacos project for type-safe backend development.

Getting Started with TypeScript

Initialize a new project with TypeScript:

xacos init my-api --ts

Project Configuration

Xacos generates a tsconfig.json with optimal settings for Node.js development:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["ES2020"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

Type Definitions

Create custom types in the src/types directory:

// src/types/user.ts
export interface User {
  id: string;
  email: string;
  name: string;
  createdAt: Date;
}

export type CreateUserDto = Omit<User, 'id' | 'createdAt'>;

Typed Controllers

import { Request, Response } from 'express';
import { User } from '../types/user';

export const getUser = async (
  req: Request,
  res: Response
): Promise<void> => {
  const user: User = await userService.findById(req.params.id);
  res.json(user);
};

Benefits

  • Catch errors at compile time
  • Better IDE autocomplete and IntelliSense
  • Refactoring with confidence
  • Self-documenting code
  • Improved maintainability

Build Commands

# Development with watch mode
npm run dev

# Production build
npm run build

# Run production build
npm start