Books/TypeScript Essentials/TypeScript Cheat Sheet for AI Prompting

    TypeScript Cheat Sheet for AI Prompting

    TypeScript Cheat Sheet for AI Prompting

    Your complete quick reference for TypeScript concepts and — most importantly — prompts to get the best results from AI coding tools. Bookmark this page!

    Basic Types

    // Primitives
    let name: string = "Alice";
    let age: number = 28;
    let active: boolean = true;
    
    // Arrays
    let names: string[] = ["Alice", "Bob"];
    let scores: number[] = [95, 87];
    
    // Union types
    let id: string | number = "abc";
    let status: "loading" | "success" | "error" = "loading";
    
    // Optional
    let nickname?: string;
    
    // Null/undefined
    let user: User | null = null;

    Interfaces & Types

    // Interface
    interface User {
      id: string;
      name: string;
      email: string;
      role: "admin" | "user";
      avatar?: string;           // Optional
    }
    
    // Type alias
    type Status = "loading" | "success" | "error";
    
    // Extending
    interface AdminUser extends User {
      permissions: string[];
    }
    
    // Utility types
    type PublicUser = Omit<User, "email">;        // Remove fields
    type UserPreview = Pick<User, "id" | "name">; // Keep only these
    type UpdateUser = Partial<User>;              // All optional

    Functions

    // Regular function
    function add(a: number, b: number): number {
      return a + b;
    }
    
    // Arrow function
    const greet = (name: string): string => `Hello, ${name}!`;
    
    // Async function
    async function getUser(id: string): Promise<User> {
      const res = await fetch(`/api/users/${id}`);
      return res.json();
    }
    
    // Callback type
    type OnChange = (value: string) => void;
    
    // Optional parameter
    function log(message: string, level?: string): void { }
    
    // Default parameter
    function log(message: string, level: string = "info"): void { }

    React Patterns

    // Component with props
    interface CardProps {
      title: string;
      children: React.ReactNode;
      onClick?: () => void;
    }
    
    const Card = ({ title, children, onClick }: CardProps) => (
      <div onClick={onClick}>
        <h2>{title}</h2>
        {children}
      </div>
    );
    
    // State
    const [count, setCount] = useState(0);
    const [user, setUser] = useState<User | null>(null);
    const [items, setItems] = useState<Item[]>([]);
    
    // Events
    const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {};
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {};
    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {};

    Backend Patterns

    // Express route
    app.get("/api/users/:id", async (req: Request<{ id: string }>, res: Response) => {
      const user = await db.getUser(req.params.id);
      res.json(user);
    });
    
    // CRUD service interface
    interface UserService {
      getAll(): Promise<User[]>;
      getById(id: string): Promise<User | null>;
      create(data: CreateUserInput): Promise<User>;
      update(id: string, data: Partial<CreateUserInput>): Promise<User>;
      delete(id: string): Promise<void>;
    }
    
    // Middleware
    const auth = (req: Request, res: Response, next: NextFunction) => {
      // verify token...
      next();
    };

    AI Prompts by Category

    Understanding Code

    • "Explain this TypeScript code in plain English. I'm a beginner: [paste code]"
    • "I see this type: [paste type]. What does each field mean?"
    • "What does Omit<User, 'password'> create? Show me the resulting type."
    • "This function returns Promise<User[]>. Walk me through what it does step by step."
    • "I see <T> in this code. What does the generic do here?"

    Starting a New Project

    • "Set up a new React project with TypeScript, Tailwind CSS, and React Router. Include the folder structure."
    • "Create a Node.js Express API with TypeScript. Set up the project structure with routes, controllers, and services."
    • "Set up a full-stack project with React frontend and Express backend, both in TypeScript. Use a monorepo structure."
    • "Initialize a Next.js project with TypeScript, Tailwind, and [database]. Include authentication."

    Building Frontend Components

    Navigation & Layout:

    • "Build a responsive navbar with logo, navigation links, and a mobile hamburger menu using React and Tailwind."
    • "Create a sidebar layout with collapsible sections. The sidebar should be closeable on mobile."
    • "Build a footer component with newsletter signup, social links, and site navigation."

    Forms & Input:

    • "Create a login form with email and password fields, validation, error messages, and a submit handler that calls /api/login."
    • "Build a multi-step registration wizard. Step 1: personal info. Step 2: preferences. Step 3: review and confirm."
    • "Create a search component with debounced input that fetches suggestions from /api/search?q= as the user types."

    Data Display:

    • "Build a product card grid that fetches from /api/products. Each card shows image, name, price, and an Add to Cart button."
    • "Create a paginated data table for users. Columns: name, email, role, joined date. Include sorting by any column."
    • "Build a dashboard with 4 stat cards at the top and a line chart showing data over time."

    Interactive Elements:

    • "Create a modal component that opens on button click, closes on backdrop click or Escape key, with a title, body, and action buttons."
    • "Build a toast notification system. Support success, error, and warning types. Auto-dismiss after 5 seconds."
    • "Create a drag-and-drop task board with columns for Todo, In Progress, and Done."

    Building Backend APIs

    CRUD Endpoints:

    • "Build a REST API for a to-do app. Todos have a title, description, status (todo/in-progress/done), and due date."
    • "Create CRUD endpoints for a blog with posts and categories. Posts belong to one category. Include pagination."
    • "Build an API for an e-commerce store: products, categories, cart, and orders."

    Authentication:

    • "Add JWT authentication to my Express API. Include signup, login, token refresh, and a middleware that protects routes."
    • "Set up Google OAuth login with Passport.js. Store users in [database]."
    • "Add role-based access control. Admin users can create/edit/delete. Regular users can only read."

    Database:

    • "Connect my Express API to PostgreSQL using Prisma. Create models for User, Post, and Comment."
    • "Set up MongoDB with Mongoose. Create schemas for Product and Order with proper TypeScript types."
    • "Create a Firestore service with typed CRUD functions for my [resource] collection."

    Advanced:

    • "Add input validation to all my endpoints using Zod. Return structured error messages."
    • "Set up file upload with Multer. Store images in [S3/Cloud Storage] and save URLs in the database."
    • "Add WebSocket support for real-time notifications when new [items] are created."

    Debugging & Fixing

    • "I'm getting this TypeScript error: [paste error]. What does it mean and how do I fix it?"
    • "This component isn't rendering correctly. Here's the code: [paste]. Can you find the bug?"
    • "My API endpoint returns 500. Here's the route handler: [paste]. Help me debug it."
    • "I'm getting Type 'X' is not assignable to type 'Y'. What's the mismatch?"
    • "My useEffect is running in an infinite loop. Here's the code: [paste]. What's wrong?"

    Refactoring & Improving

    • "This component is getting too long. Can you split it into smaller, reusable components?"
    • "Add proper TypeScript types to this JavaScript code: [paste code]."
    • "This code works but has a lot of repetition. Can you refactor it to be DRY?"
    • "Add error handling and loading states to this data-fetching component."
    • "Convert these API calls to use React Query for caching and automatic refetching."

    TypeScript Error Quick Fixes

    Error MessageWhat It MeansQuick Fix
    Type 'X' is not assignable to type 'Y'Wrong type somewhereCheck that values match expected types
    Property 'X' does not exist on type 'Y'Accessing a field that isn't definedAdd the field to the interface or check for typos
    Argument of type 'X' is not assignablePassing wrong type to a functionCheck what the function expects
    Object is possibly 'null'Value might be nullAdd a null check (if (value) {...})
    Object is possibly 'undefined'Value might not existAdd optional chaining (value?.property)
    Cannot find module 'X'Missing import or packageInstall the package or fix the import path

    What to ask your AI: "I'm getting this TypeScript error: [paste the full error message]. Can you explain what's wrong and how to fix it?"

    The Complete Beginner Workflow

    When working with AI on a TypeScript project:

    1. DESCRIBE what you want to build (be specific!)
    2. READ the generated code — look for interfaces to understand the data shapes
    3. ASK about anything you don't understand
    4. TEST the code — run it and see if it works
    5. ITERATE — tell the AI what to change or fix
    

    The key insight: You don't need to write TypeScript perfectly. You need to:

    • Read it well enough to understand what AI generated
    • Describe what you want clearly enough for AI to generate it
    • Recognize when something looks wrong and ask about it

    Keep Learning

    TypeScript has much more to offer as you grow:

    • Generics for reusable, type-safe functions
    • Enums for named constants
    • Type guards for runtime type checking
    • Mapped types for advanced type transformations

    But you don't need any of that to start building. Use these basics, lean on your AI tools, and learn more as you encounter new patterns.

    Remember: Every senior TypeScript developer once Googled "TypeScript type error I don't understand." With AI tools, you can learn and build faster than ever.

    Happy building!


    🌐 www.genai-mentor.ai