Intermediate

Code Generation

Learn to generate functions, tests, documentation, boilerplate code, APIs, and entire project scaffolds using Copilot Chat's powerful code generation capabilities.

Generating New Projects with /new

The /new slash command scaffolds entire projects from a description. Copilot Chat creates the file structure, boilerplate code, and configuration files for you.

Chat Prompt
/new Create a Node.js Express REST API with TypeScript,
including user authentication with JWT, a MongoDB
connection, and organized routes/controllers/models

Copilot will propose a project structure like this and generate all the files:

Generated Project Structure
my-api/
  src/
    controllers/
      authController.ts
      userController.ts
    models/
      User.ts
    routes/
      authRoutes.ts
      userRoutes.ts
    middleware/
      auth.ts
    config.ts
    app.ts
    server.ts
  package.json
  tsconfig.json
  .env.example
Be specific: The more detail you provide in your /new prompt, the better the generated project matches your needs. Include the tech stack, architecture patterns, and any specific libraries you want.

Writing Functions from Descriptions

Describe what a function should do in plain English, and Copilot Chat will generate the implementation. You can do this in the chat panel or via inline chat.

Chat Prompt
// Chat prompt:
Write a TypeScript function that takes an array of
objects with 'name' and 'score' properties, groups
them by score ranges (0-59: F, 60-69: D, 70-79: C,
80-89: B, 90-100: A), and returns a Map of grade
letters to arrays of names.
Generated TypeScript
interface Student {
  name: string;
  score: number;
}

function groupByGrade(students: Student[]): Map<string, string[]> {
  const gradeMap = new Map<string, string[]>();

  const getGrade = (score: number): string => {
    if (score >= 90) return 'A';
    if (score >= 80) return 'B';
    if (score >= 70) return 'C';
    if (score >= 60) return 'D';
    return 'F';
  };

  for (const student of students) {
    const grade = getGrade(student.score);
    const names = gradeMap.get(grade) || [];
    names.push(student.name);
    gradeMap.set(grade, names);
  }

  return gradeMap;
}

Generating Tests with /tests

The /tests slash command generates unit tests for selected code. Select a function or class in your editor, then use /tests in the chat panel.

Chat Prompt
/tests Generate comprehensive tests for the groupByGrade
function including edge cases like empty arrays,
boundary scores (59, 60, 89, 90), and invalid scores
Generated Tests
import { groupByGrade } from './grading';

describe('groupByGrade', () => {
  it('should group students by grade correctly', () => {
    const students = [
      { name: 'Alice', score: 95 },
      { name: 'Bob', score: 82 },
      { name: 'Charlie', score: 67 },
    ];
    const result = groupByGrade(students);
    expect(result.get('A')).toEqual(['Alice']);
    expect(result.get('B')).toEqual(['Bob']);
    expect(result.get('D')).toEqual(['Charlie']);
  });

  it('should handle empty array', () => {
    const result = groupByGrade([]);
    expect(result.size).toBe(0);
  });

  it('should handle boundary scores', () => {
    const students = [
      { name: 'Edge1', score: 90 },
      { name: 'Edge2', score: 89 },
      { name: 'Edge3', score: 60 },
      { name: 'Edge4', score: 59 },
    ];
    const result = groupByGrade(students);
    expect(result.get('A')).toEqual(['Edge1']);
    expect(result.get('B')).toEqual(['Edge2']);
    expect(result.get('D')).toEqual(['Edge3']);
    expect(result.get('F')).toEqual(['Edge4']);
  });
});
💡
Testing frameworks: Copilot Chat detects the testing framework in your project (Jest, Mocha, Vitest, pytest, JUnit, etc.) and generates tests using the appropriate syntax and assertions.

Adding Documentation with /doc

The /doc command generates documentation comments for your code. Select a function, class, or method and use /doc.

Chat Prompt
/doc Add JSDoc documentation with @param, @returns,
@throws, and @example tags
Generated Documentation
/**
 * Groups students by their letter grade based on score ranges.
 *
 * Grade ranges: A (90-100), B (80-89), C (70-79), D (60-69), F (0-59)
 *
 * @param students - Array of student objects with name and score
 * @returns Map of grade letters to arrays of student names
 * @throws {TypeError} If students is not an array
 *
 * @example
 * const students = [
 *   { name: 'Alice', score: 95 },
 *   { name: 'Bob', score: 72 }
 * ];
 * const grades = groupByGrade(students);
 * // grades.get('A') => ['Alice']
 * // grades.get('C') => ['Bob']
 */

Generating Boilerplate Code

Copilot Chat excels at generating repetitive boilerplate code. Instead of manually writing CRUD operations, form handlers, or configuration files, describe what you need.

Boilerplate Examples
// CRUD operations
Create a complete CRUD service for a Product entity
with fields: id, name, price, category, createdAt

// React component
Create a React form component with validation for
user registration (name, email, password, confirm password)

// Configuration
Generate a Docker Compose file with Node.js app,
PostgreSQL database, and Redis cache

// CI/CD
Create a GitHub Actions workflow for a Node.js app
with lint, test, build, and deploy stages

Creating APIs, Components, and Models

For larger code generation tasks, provide detailed specifications. Copilot Chat can generate interconnected code across multiple concerns.

API Generation Example
// Generate a complete API endpoint
Create a REST API endpoint for managing blog posts:
- GET /posts (list with pagination and filtering)
- GET /posts/:id (single post with comments)
- POST /posts (create, requires auth)
- PUT /posts/:id (update, requires auth + ownership)
- DELETE /posts/:id (soft delete, requires auth + ownership)

Use Express with TypeScript, Prisma ORM, and Zod
for request validation.

Multi-File Generation

Copilot Chat can generate code that spans multiple files. Use @workspace /new for project scaffolding, or describe multi-file changes in the chat panel.

Multi-File Generation
@workspace Create a complete authentication module with:
1. A User model (user.model.ts)
2. Auth controller (auth.controller.ts)
3. Auth routes (auth.routes.ts)
4. JWT middleware (jwt.middleware.ts)
5. Validation schemas (auth.validation.ts)
6. Unit tests for the auth controller
Always review generated code: Copilot Chat generates code based on patterns and context, but it may not always match your exact requirements. Always review, test, and adjust generated code before committing it to your project.

💡 Try It: Generate a Utility Function

Open the chat panel and ask Copilot Chat to generate a utility function. Try this prompt or create your own:

After generating the code, use /tests to generate tests for it, and /doc to add documentation. This three-step workflow (generate, test, document) is one of the most powerful patterns in Copilot Chat.