Introduction
If you write JavaScript or TypeScript daily—whether it’s React components, Node.js middleware, or utility libraries—you’ve likely experienced the friction of boilerplate, repetitive patterns, or just staring at an empty editor. AI-powered code generation, when prompted correctly, can cut that friction by 50–70%. But the difference between a useless or even harmful output and a production-ready snippet often lies in the prompt itself.
I’ve compiled 12 battle-tested prompts I use in my own workflow. Each one is specific, includes constraints, and outputs code that follows modern best practices (ES2022+, strict TypeScript, proper error handling). No fluff—just prompts that work.
1. Generate a React Component with Full TypeScript Props
Prompt:
Create a React component in TypeScript that renders a debounced search input. The component should:
- Accept props: placeholder (string), onSearch (callback with value: string)
- Use useCallback and useEffect for debouncing (300ms)
- Include a clear button that resets the input
- Export the type for props
- Use React 18+ patterns (no class components)
Example output (abbreviated):
import { useState, useCallback, useEffect } from 'react';
export type SearchInputProps = {
placeholder?: string;
onSearch: (value: string) => void;
};
export const SearchInput = ({ placeholder = 'Search...', onSearch }: SearchInputProps) => {
const [value, setValue] = useState('');
const debouncedSearch = useCallback(
(val: string) => {
const timer = setTimeout(() => onSearch(val), 300);
return () => clearTimeout(timer);
},
[onSearch]
);
useEffect(() => {
const cleanup = debouncedSearch(value);
return cleanup;
}, [value, debouncedSearch]);
return (
<div>
<input value={value} onChange={(e) => setValue(e.target.value)} placeholder={placeholder} />
{value && <button onClick={() => setValue('')}>Clear</button>}
</div>
);
};
2. Write a Node.js Middleware for JWT Authentication
Prompt:
Generate an Express middleware in TypeScript that:
- Extracts a JWT token from the Authorization header (Bearer scheme)
- Verifies the token using jsonwebtoken library
- Attaches the decoded user payload to req.user
- Returns 401 with a clear error message if token is missing or invalid
- Includes proper TypeScript types for the request extension
- Handles edge cases: malformed token, expired token, no header
3. Create a Custom React Hook for Fetching Data
Prompt:
Write a TypeScript custom hook called useFetch that:
- Takes a URL string and optional AbortSignal
- Returns { data, error, isLoading } with proper generics
- Handles race conditions (stale responses) via AbortController
- Re-fetches when URL changes
- Uses async/await with try/catch
- Does NOT use any external library (just fetch)
4. Generate a Utility Function for Deep Object Cloning
Prompt:
Create a TypeScript utility function deepClone<T>(obj: T): T that:
- Handles nested objects, arrays, Date, Map, Set, RegExp
- Does not use JSON.parse/JSON.stringify (to preserve special types)
- Throws on circular references
- Is fully typed with generics
- Includes JSDoc comments
5. Write a React Native Component with Platform-Specific Styles
Prompt:
Generate a React Native component in TypeScript that displays a card with a shadow. Use StyleSheet.create with platform-specific values (iOS shadow vs Android elevation). The card should have:
- title (string)
- description (string)
- onPress callback
- Proper typing for TouchableOpacity props
6. Create a TypeScript Decorator for Logging
Prompt:
Write a TypeScript method decorator called @LogExecutionTime that:
- Logs the method name and execution time in milliseconds
- Works with async methods (awaits result)
- Preserves the original method's type signature
- Uses console.time and console.timeEnd
- Includes proper typing for the decorator factory
7. Generate a Redux Toolkit Slice with Async Thunk
Prompt:
Create a Redux Toolkit slice in TypeScript for a 'users' entity. Include:
- State: { items: User[], loading: boolean, error: string | null }
- Async thunk: fetchUsers that calls an API (https://jsonplaceholder.typicode.com/users)
- Extra reducers for pending, fulfilled, rejected
- Proper typing for the thunkAPI rejectValue
- Export the slice reducer and actions
8. Write a Zod Schema for a Complex API Response
Prompt:
Define a Zod schema in TypeScript for a paginated API response:
- data: array of objects with id (number), name (string), email (email format), role (enum: 'admin'
| 'user' | 'moderator')
- pagination: { page, perPage, total }
- Infer the TypeScript type from the schema
- Include a refinement that checks total >= 0
9. Create a Singleton Pattern Utility Class
Prompt:
Write a TypeScript generic class Singleton<T> that:
- Accepts a constructor function as argument
- Returns the same instance on every instantiation
- Is thread-safe (for Node.js, since JS is single-threaded, just ensure it works with async init)
- Has a reset method for testing
- Export the class and a helper function createSingleton
10. Generate a Custom ESLint Rule in TypeScript
Prompt:
Create an ESLint rule (in TypeScript) that flags console.log statements in production code. The rule should:
- Use AST selectors to find CallExpression with callee name 'console.log'
- Only flag it if there's no comment /* allow-console */ on the same line
- Provide a fixer that removes the console.log call
- Include proper meta with type 'suggestion' and fixable: 'code'
- Export the rule as default
11. Write a WebSocket Client Wrapper in TypeScript
Prompt:
Generate a TypeScript class WebSocketClient that:
- Connects to a given URL with automatic reconnection (exponential backoff)
- Emits typed events (onMessage, onOpen, onClose, onError)
- Has send(data) method that queues messages if not connected
- Uses generics for message types
- Handles cleanup on unmount (close connection)
12. Create a Performance Benchmarking Script
Prompt:
Write a Node.js script in TypeScript that benchmarks two functions (sync and async). It should:
- Accept the functions as arguments
- Run each function N times (configurable, default 1000)
- Calculate and print: average time, median, min, max, and standard deviation
- Use performance.now() for timing
- Output a Markdown-formatted table
- Include proper error handling (skip failed runs)
Conclusion
These 12 prompts aren’t magic—they’re structured. The key is specificity: type constraints, error handling, edge cases, and real-world patterns. Copy them, adapt them to your project, and you’ll save hours of boilerplate.
If you found this useful, share it with a teammate who still writes components by hand. And if you have a killer prompt of your own, drop it in the comments below.
Comments