logo
🤖 AI 工具

GitHub Copilot

GitHub Copilot Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · AI 工具🧭 Markdown 速查🏷️ 3 个标签
#ai#coding#github
向下滚动查看内容
返回全部 Cheat Sheets

Overview

What is GitHub Copilot
  • AI coding assistant by GitHub and OpenAI
  • Trained on public code repositories
  • Supports multiple IDEs and languages
  • Provides code completion, generation, explanation
Supported IDEs
IDESupport Level
VS CodeFull support
Visual StudioFull support
JetBrains IDEsFull support
NeovimPlugin support
Azure Data StudioSupported
Supported Languages
  • JavaScript/TypeScript
  • Python
  • Java
  • C/C++/C#
  • Go
  • Ruby
  • PHP
  • And many more...

VS Code Shortcuts

Code Completion
ShortcutAction
TabAccept suggestion
EscDismiss suggestion
Alt + ]Next suggestion
Alt + [Previous suggestion
Alt + \Trigger suggestion
Ctrl + EnterView all suggestions
Copilot Chat
ShortcutAction
Ctrl + IInline Chat
Ctrl + Shift + IOpen Chat panel
Ctrl + LClear Chat
Code Actions
ShortcutAction
Ctrl + Shift + Alt + EExplain code
Ctrl + Shift + Alt + FFix code
Ctrl + Shift + Alt + TGenerate tests
Ctrl + Shift + Alt + DGenerate docs

JetBrains Shortcuts

Code Completion
ShortcutAction
TabAccept suggestion
EscDismiss suggestion
Alt + ]Next suggestion
Alt + [Previous suggestion
Alt + \Manual trigger
Chat
ShortcutAction
Ctrl + Shift + COpen Copilot Chat

Completion Techniques

Comment-Driven Development

Function Description

PYTHON
滚动查看更多
# Calculate the factorial of a number recursively
# Handle edge cases for negative numbers
def factorial(n):
    # Copilot completes the implementation

Detailed Specification

JAVASCRIPT
滚动查看更多
// Send POST request to specified URL
// Parameters: url - request URL, data - request body
// Returns: Promise<Response>
// Throws: NetworkError if request fails
async function postData(url, data) {

Algorithm Description

PYTHON
滚动查看更多
# Implement binary search on sorted array
# Return index if found, -1 otherwise
# Time complexity: O(log n)
def binary_search(arr, target):

Data Transformation

JAVASCRIPT
滚动查看更多
// Convert array of objects to lookup map
// Input: [{id: 1, name: 'a'}, {id: 2, name: 'b'}]
// Output: {1: {id: 1, name: 'a'}, 2: {id: 2, name: 'b'}}
function arrayToMap(arr, key) {
Function Signature Guidance

Clear Naming

TYPESCRIPT
滚动查看更多
function calculateTotalPriceWithTax(
    items: CartItem[],
    taxRate: number
): number {

Type Annotations

PYTHON
滚动查看更多
def send_email(
    to: str,
    subject: str,
    body: str,
    attachments: list[str] | None = None
) -> bool:

Descriptive Parameters

JAVASCRIPT
滚动查看更多
function filterUsersByAge(
    users,          // Array of user objects
    minAge,         // Minimum age (inclusive)
    maxAge          // Maximum age (inclusive)
) {
Context Hints

Related Imports

JAVASCRIPT
滚动查看更多
import { useState, useEffect } from 'react';
import axios from 'axios';

// Copilot understands you're writing React + API
function UserList() {

Adjacent Code

PYTHON
滚动查看更多
users = fetch_users()
emails = [u.email for u in users]

# Copilot uses context for better completion
active_users = users.filter(

Existing Patterns

TYPESCRIPT
滚动查看更多
// Following existing code pattern
const getUser = (id: string) => api.get(`/users/${id}`);
const getPosts = (id: string) => api.get(`/posts/${id}`);

// Copilot follows the pattern
const getComments =

Copilot Chat

Opening Chat

VS Code:

CODE
滚动查看更多
Ctrl + Shift + I  or
Click Copilot icon in sidebar
Slash Commands

Explain Code

CODE
滚动查看更多
/explain
Select code and use this command

Fix Issues

CODE
滚动查看更多
/fix
Automatically identify and fix problems

Generate Tests

CODE
滚动查看更多
/tests
Generate tests for selected code

Generate Docs

CODE
滚动查看更多
/doc
Generate documentation comments

Optimize

CODE
滚动查看更多
@workspace /optimize
Optimize selected code

Simplify

CODE
滚动查看更多
/simplify
Simplify complex code

New File

CODE
滚动查看更多
/new
Create a new file with specified content
@ Context References

Workspace

CODE
滚动查看更多
@workspace explain the project structure

Terminal

CODE
滚动查看更多
@terminal the last command failed, how do I fix it?

VS Code

CODE
滚动查看更多
@vscode how do I configure auto-format on save?

File

CODE
滚动查看更多
@file:src/index.ts explain this file
Inline Chat
  1. Select code
  2. Press Ctrl + I
  3. Type instruction
  4. Review and accept changes

Common Instructions:

CODE
滚动查看更多
add error handling
CODE
滚动查看更多
convert to async/await
CODE
滚动查看更多
add type annotations
CODE
滚动查看更多
make this more readable

Code Generation

From Comments

JavaScript Function

JAVASCRIPT
滚动查看更多
// Validate email format
// Return true if valid, false otherwise
function validateEmail(email) {
	// Copilot generates regex validation
}

Python Class

PYTHON
滚动查看更多
# User class with the following properties:
# - id: user ID (int)
# - name: username (str)
# - email: email address (str)
# - created_at: creation timestamp
# Methods: to_dict(), from_dict()
class User:

React Component

JSX
滚动查看更多
// UserCard component
// Props: user object with name, avatar, bio
// Display user info in a card layout
// Include edit button if isEditable is true
function UserCard({ user, isEditable }) {

API Endpoint

PYTHON
滚动查看更多
# FastAPI endpoint for user registration
# Accept: email, password, name
# Validate: email format, password strength
# Return: user object with JWT token
@app.post("/register")
async def register(
From Function Names
TYPESCRIPT
滚动查看更多
function sortByDateDescending(items: Item[]): Item[] {

function filterActiveSubscribers(users: User[]): User[] {

function calculateMonthlyRevenue(orders: Order[]): number {

function groupByCategory<T>(items: T[], key: keyof T): Record<string, T[]> {
Test Generation

Jest Tests

JAVASCRIPT
滚动查看更多
// test for validateEmail function
describe('validateEmail', () => {
	// Copilot generates test cases:
	// - valid email
	// - invalid format
	// - empty string
	// - edge cases
});

Pytest

PYTHON
滚动查看更多
# pytest tests for User class
class TestUser:
    # Copilot generates test methods:
    # - test_create_user
    # - test_to_dict
    # - test_from_dict
    # - test_invalid_email
Documentation

JSDoc

JAVASCRIPT
滚动查看更多
/**
 * [Cursor here, Copilot completes]
 */
function processOrder(order, options) {

Python Docstring

PYTHON
滚动查看更多
def calculate_discount(price, percentage, max_discount=None):
    """
    [Copilot completes docstring with:
    - Description
    - Args
    - Returns
    - Raises
    - Examples]
    """

TypeScript Interface

TYPESCRIPT
滚动查看更多
/**
 * [Copilot generates interface documentation]
 */
interface PaymentRequest {
	amount: number;
	currency: string;
	customerId: string;
}

Prompt Examples

Code Review
CODE
滚动查看更多
/explain
Review this code for:
- Potential bugs
- Performance issues
- Security vulnerabilities
- Best practice violations
Refactoring
CODE
滚动查看更多
Select code → Ctrl + I → Type:
"refactor to use async/await instead of promises"
CODE
滚动查看更多
"extract repeated logic into a helper function"
CODE
滚动查看更多
"convert to functional programming style"
Learning New APIs
CODE
滚动查看更多
/explain
How does this library's authentication work?
Show me usage examples.
Error Fixing
CODE
滚动查看更多
@terminal
I got this error:
ModuleNotFoundError: No module named 'requests'

How do I fix it?
Performance Optimization
CODE
滚动查看更多
/optimize
This function is slow with large datasets.
How can I improve its performance?
Security Review
CODE
滚动查看更多
@workspace
Review this authentication code for security issues.
Focus on:
- SQL injection
- XSS vulnerabilities
- Secure password handling

Configuration

VS Code Settings

Enable/Disable

JSON
滚动查看更多
{
	"github.copilot.enable": {
		"*": true,
		"markdown": false,
		"plaintext": false
	}
}

Inline Suggestions

JSON
滚动查看更多
{
	"github.copilot.inlineSuggest.enable": true
}
Project Instructions

Create .github/copilot-instructions.md:

MARKDOWN
滚动查看更多
# Copilot Instructions

Code Style

  • Use TypeScript for all files
  • Follow ESLint rules
  • Use functional programming style
  • Prefer immutable data structures

Naming Conventions

  • Variables: camelCase
  • Constants: UPPER_SNAKE_CASE
  • Classes: PascalCase
  • Files: kebab-case

Testing Requirements

  • Use Jest framework
  • Cover edge cases
  • Include error handling tests
  • Aim for 80% coverage

Documentation

  • JSDoc for public functions
  • Inline comments for complex logic
  • README for each module
CODE
滚动查看更多

Best Practices

Improving Suggestions
  1. Write clear comments

    • Describe function purpose
    • Specify parameters and returns
    • Provide usage examples
  2. Use meaningful names

    • Functions describe behavior
    • Variables express meaning
    • Complete type annotations
  3. Maintain relevant context

    • Import related libraries
    • Define related types
    • Provide example data
Code Review Prompts
CODE
滚动查看更多
Select code → Ctrl + I →
"review for potential issues and suggest improvements"
Learning New Codebase
CODE
滚动查看更多
@workspace
I'm new here. Explain:
- Project structure
- Key patterns used
- How to add a new feature

CLI Tool

Installation
BASH
滚动查看更多
gh extension install github/gh-copilot
Common Commands

Explain Command

BASH
滚动查看更多
gh copilot explain "git rebase -i HEAD~3"

Suggest Command

BASH
滚动查看更多
gh copilot suggest "find files larger than 100MB"
Aliases
BASH
滚动查看更多
# Add to .bashrc or .zshrc
alias '??'='gh copilot suggest -t shell'
alias 'git?'='gh copilot suggest -t git'
alias 'gh?'='gh copilot suggest -t gh'
Example Usage
BASH
滚动查看更多
# Get shell command suggestions
?? "compress all images in current directory"

# Get git command help
git? "undo last commit but keep changes"

# Get GitHub CLI help
gh? "list my open pull requests"

Troubleshooting

Inaccurate Suggestions
  • Add more context
  • Write detailed comments
  • Use Alt + ] to cycle suggestions
  • Try rephrasing your comment
Slow Suggestions
  • Check network connection
  • Reduce number of open files
  • Restart IDE
No Suggestions
  • Confirm Copilot is enabled
  • Check file type is supported
  • Check status bar Copilot icon
Privacy Considerations
  • Disable Copilot for sensitive code
  • Check organization policies
  • Use .gitignore to exclude sensitive files

相关 Cheat Sheets

1v1免费职业咨询
logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2025 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572