DevToolBoxGRATIS
Blogg

GitHub Copilot Tips 2026: Prompt Engineering, Chat og Agentmodus

11 minby DevToolBox

GitHub Copilot has become an essential tool for developers, boosting productivity by 30-55% according to studies. However, many developers only scratch the surface of what Copilot can do. This guide covers advanced techniques, prompt engineering strategies, and workflow integrations that will help you get the most out of your AI pair programmer in 2026.

How GitHub Copilot Works

Copilot uses large language models trained on public code repositories to generate code suggestions. It analyzes your current file, open tabs, recent edits, and comments to predict what you want to write next. Understanding how it works helps you write better prompts and get better suggestions.

Context Window

Copilot considers several sources of context when generating suggestions: the current file (most important), open tabs in your editor, the file path and name, imported modules, and recent edit history. Maximizing the quality of these context signals improves suggestions.

// Copilot context sources (ranked by importance):
// 1. Current file content (most important)
// 2. File name and path (e.g., src/utils/date.ts hints at date utilities)
// 3. Open tabs in your editor
// 4. Imported modules and their types
// 5. Recent edits and cursor position
// 6. Comments and JSDoc annotations

// PRO TIP: Name your files descriptively
// "helpers.ts" -> vague context
// "date-formatting-utils.ts" -> Copilot knows to suggest date formatting code

Prompt Engineering for Copilot

The quality of Copilot suggestions depends heavily on how you write your code and comments. Think of every comment, function name, and type annotation as a prompt to the AI.

Comment-Driven Development

Write descriptive comments before your code to guide Copilot. The more specific your comment, the more accurate the generated code.

// BAD: vague comment
// sort the data
function sortData(data) { ... }

// GOOD: specific comment with details
// Sort users by last login date, most recent first.
// Users who have never logged in should appear at the end.
// Preserve original array (return new sorted array).
function sortUsersByLastLogin(users: User[]): User[] {
  // Copilot will generate accurate sorting logic
}

// GREAT: step-by-step comments for complex logic
// 1. Filter out inactive users (status !== "active")
// 2. Group remaining users by department
// 3. Sort each group by join date (ascending)
// 4. Return a Map<department, User[]>
function organizeActiveUsers(users: User[]): Map<string, User[]> {
  // Copilot follows the steps precisely
}

Function Signatures as Prompts

Well-typed function signatures with descriptive parameter names are powerful prompts. Copilot uses the name, parameters, return type, and JSDoc comments to infer what the function should do.

// Type annotations guide Copilot significantly

// BAD: no types, vague name
function process(data) { ... }

// GOOD: typed, descriptive name
function calculateMonthlyRevenue(
  transactions: Transaction[],
  month: number,
  year: number
): { total: number; count: number; average: number } {
  // Copilot will generate accurate calculation logic
}

// JSDoc enhances suggestions further
/**
 * Converts a file size in bytes to a human-readable string.
 * @param bytes - File size in bytes
 * @param decimals - Number of decimal places (default: 2)
 * @returns Human-readable string like "1.5 MB" or "300 KB"
 * @example formatBytes(1536) // "1.5 KB"
 * @example formatBytes(1073741824) // "1 GB"
 */
function formatBytes(bytes: number, decimals = 2): string {
  // Copilot generates the exact implementation
}

Provide Examples

When Copilot does not generate the right code on the first try, provide an example of the expected input/output. Copilot is excellent at pattern recognition and will follow the established pattern.

// Provide examples for pattern-based code generation

// Convert snake_case to camelCase
// "user_name" -> "userName"
// "first_name_last" -> "firstNameLast"
// "already_camelCase" -> "alreadyCamelCase"
function snakeToCamel(str: string): string {
  // Copilot follows the pattern from examples
}

// Generate test data following a pattern
const testUsers = [
  { id: 1, name: "Alice", email: "alice@example.com", role: "admin" },
  { id: 2, name: "Bob", email: "bob@example.com", role: "user" },
  // Copilot continues the pattern...
  // { id: 3, name: "Charlie", email: "charlie@example.com", role: "user" },
];

Essential Keyboard Shortcuts

Master these shortcuts to work efficiently with Copilot.

ActionMacWindows/Linux
Accept suggestionTabTab
Dismiss suggestionEscEsc
Next suggestionOption + ]Alt + ]
Previous suggestionOption + [Alt + [
Open Copilot panel (10 suggestions)Ctrl + EnterCtrl + Enter
Inline ChatCmd + ICtrl + I
Open Copilot ChatCmd + Shift + ICtrl + Shift + I
Accept wordCmd + Right ArrowCtrl + Right Arrow
Accept lineCmd + EndEnd

Copilot Chat

Copilot Chat provides an interactive AI assistant directly in your editor. It can explain code, fix bugs, generate tests, and answer questions about your codebase.

Slash Commands

Copilot Chat supports slash commands for common tasks. These provide structured interactions that produce better results than free-form questions.

// Copilot Chat slash commands (type in chat panel):

/explain    - Explain how the selected code works
/fix        - Propose a fix for problems in the selected code
/tests      - Generate unit tests for the selected code
/doc        - Generate documentation for the selected code
/optimize   - Analyze and improve performance of selected code
/clear      - Clear the chat history
/new        - Scaffold a new project or file

// Examples:
// Select a function, then type: /explain
// Select buggy code, then type: /fix
// Select a class, then type: /tests using vitest
// Type: /new create a REST API with Express and TypeScript

Context References

Use @ references to point Copilot Chat at specific context: @workspace for the whole project, @file for specific files, @terminal for terminal output, and @selection for selected code.

// Context references in Copilot Chat:

@workspace  - Search and reference your entire workspace
@file       - Reference a specific file
@terminal   - Reference terminal output
@selection  - Reference currently selected code

// Examples:
// "How does authentication work in @workspace?"
// "What does @file:src/utils/auth.ts do?"
// "Fix the error shown in @terminal"
// "Refactor @selection to use async/await"

// Combining references for powerful queries:
// "Based on @file:src/types.ts, generate CRUD endpoints
//  for the User type in @file:src/routes/users.ts"

Advanced Patterns

Test Generation

Copilot excels at generating tests. Provide the function to test and a clear description of the expected behavior.

// Tip: Write one test manually, Copilot generates the rest

import { describe, it, expect } from "vitest";
import { formatBytes } from "./utils";

describe("formatBytes", () => {
  it("should format bytes correctly", () => {
    expect(formatBytes(0)).toBe("0 Bytes");
  });

  // Copilot generates remaining tests:
  it("should format kilobytes", () => {
    expect(formatBytes(1024)).toBe("1 KB");
  });

  it("should format megabytes", () => {
    expect(formatBytes(1048576)).toBe("1 MB");
  });

  it("should handle decimal places", () => {
    expect(formatBytes(1536, 1)).toBe("1.5 KB");
  });

  it("should handle negative numbers", () => {
    expect(formatBytes(-1)).toBe("0 Bytes");
  });
});

Regular Expression Help

Copilot is particularly good at writing and explaining regular expressions. Describe what you want to match in natural language.

// Describe what you want to match in natural language:

// Match email addresses (RFC 5322 simplified)
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

// Match US phone numbers: (555) 123-4567, 555-123-4567, 5551234567
const phoneRegex = /^\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;

// Match ISO 8601 datetime: 2026-02-23T10:30:00Z
const isoDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;

// Match semantic version: 1.2.3, 1.0.0-beta.1, 2.1.0+build.123
const semverRegex = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?(\+[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;

Best Practices

  • Always review generated code carefully before accepting. Copilot can produce plausible but incorrect code.
  • Keep open tabs relevant. Close unrelated files to improve context quality.
  • Use TypeScript for better suggestions. Type annotations dramatically improve Copilot accuracy.
  • Write specific comments. "Sort users by age descending" is better than "sort users".
  • Reject and re-prompt if the first suggestion is wrong. Copilot often improves on retry.
  • Use Copilot Chat for complex tasks instead of inline suggestions.
  • Create a Copilot instructions file (.github/copilot-instructions.md) for project-specific guidance.
  • Do not use Copilot for security-sensitive code without expert review.
  • Leverage Copilot for boilerplate, test generation, and documentation while focusing your effort on architecture and business logic.

Security Considerations

While Copilot is powerful, it requires careful attention to security.

  • Never accept suggested credentials, API keys, or secrets without reviewing them
  • Copilot may suggest code with known vulnerabilities (SQL injection, XSS, etc.)
  • Always validate and sanitize user input, even in Copilot-generated code
  • Review cryptographic code suggestions with a security expert
  • Use Copilot Content Exclusions to prevent sensitive files from being sent to the model
  • Enable code scanning to catch security issues in generated code

Copilot Workspace and Agent Mode

GitHub Copilot continues to evolve beyond code completion. Copilot Workspace allows you to plan, implement, and review changes across entire repositories using natural language. Agent mode enables Copilot to autonomously complete multi-step tasks.

Copilot Workspace

Copilot Workspace takes a GitHub issue and generates a plan, specifies file changes, implements the changes, and creates a pull request. You review and refine at each step.

Agent Mode in VS Code

Agent mode allows Copilot to autonomously execute multi-step tasks: running terminal commands, reading/editing files, and iterating based on errors. It is like having a junior developer that follows instructions.

// Agent mode example prompts:

// "Add input validation to all API endpoints in src/routes/"
// -> Copilot scans files, adds Zod validation, runs tests

// "Refactor the auth module to use JWT instead of sessions"
// -> Copilot plans changes, modifies files, updates tests

// "Fix the failing CI tests in the latest PR"
// -> Copilot reads test output, identifies issues, applies fixes

// "Add dark mode support to all components"
// -> Copilot identifies components, adds theme variables, tests

// Agent mode workflow:
// 1. You describe the task in natural language
// 2. Copilot creates a plan with file changes
// 3. You review and approve the plan
// 4. Copilot executes: edits files, runs commands, iterates on errors
// 5. You review the final result

Frequently Asked Questions

Is GitHub Copilot worth the $10/month?

For professional developers, yes. Studies show Copilot increases productivity by 30-55% and significantly reduces time spent on boilerplate code, test writing, and documentation. The free tier (Copilot Free, 2000 completions/month) is enough for light use. The Individual plan ($10/month) is ideal for most developers. Business ($19/user/month) adds policy controls and enterprise features.

Does Copilot work with all programming languages?

Copilot supports all major programming languages but works best with languages well-represented in its training data: TypeScript, JavaScript, Python, Go, Rust, Java, C++, C#, Ruby, and PHP. It also works with markup languages (HTML, CSS, SQL), configuration formats (YAML, JSON, TOML), and shell scripts.

Can Copilot understand my entire codebase?

Copilot has a limited context window (currently several thousand tokens). It primarily uses the current file, open tabs, and recent edits. For broader codebase understanding, use Copilot Chat with @workspace to search across your project. Copilot does not have persistent memory of your codebase between sessions.

Is code generated by Copilot safe to use in proprietary projects?

GitHub states that Copilot suggestions are generated and not copied from specific repositories. The Copilot Individual and Business plans include a filter to block suggestions matching public code. However, you are responsible for reviewing generated code for correctness, security, and licensing compliance. Enable the duplicate detection filter for added protection.

What is the difference between Copilot and ChatGPT for coding?

Copilot is integrated into your editor and provides real-time suggestions with direct access to your codebase context (open files, project structure). ChatGPT requires copy-pasting code and lacks editor integration. Copilot is better for inline coding, while ChatGPT is better for architectural discussions, learning concepts, and debugging conversations.

𝕏 Twitterin LinkedIn
Var dette nyttig?

Hold deg oppdatert

Få ukentlige dev-tips og nye verktøy.

Ingen spam. Avslutt når som helst.

Try These Related Tools

±Text Diff Checker{ }JSON Formatter#Hash Generator

Related Articles

TypeScript 5 Nye Funksjoner: Dekoratorer, Const Type-parametere og Satisfies

Komplett guide til TypeScript 5 nyheter: dekoratorer, const type params og satisfies.

Git-branching-strategier: GitFlow vs Trunk-Based vs GitHub Flow

Sammenlign GitFlow, Trunk-Based Development og GitHub Flow. Branch-strukturer, merge-arbeidsflyter, CI/CD-integrasjon og aa velge riktig strategi for teamet ditt.

Zod Valideringsguide: Skjemaer, Transformasjoner, Refinements og tRPC

Mestre Zod skjemavalidering i TypeScript: skjemaer, transformasjoner, refinements og tRPC.