15 Prompts for JavaScript and TypeScript Code Generation

Why Prompts Matter for Code Generation

AI code assistants are now a standard part of the developer workflow. According to the JetBrains Developer Ecosystem survey, a significant majority of developers use AI tools daily to write or review code. But the difference between a generic autocomplete and a powerful code generator lies in the prompt. A well-crafted prompt provides context, constraints, and expected output, turning the assistant into a senior engineer who writes idiomatic React, Node.js, and TypeScript.

This collection contains 15 battle-tested prompts that I use in production. They are not abstract examples; each solves a real problem and can be copied with minor adjustments. All examples use TypeScript, because types improve maintainability and make AI-generated code safer.

React Components

1. Modal with Focus Trap

Prompt: "Generate a reusable React modal component using TypeScript. It must close on Escape, trap focus using the inert attribute, and lock body scroll. Use hooks only."

Result: A functional Modal component with useEffect for event listeners and useRef for focus management. The output typically includes a createPortal call and proper cleanup.

2. Custom useFetch Hook

Prompt: "Create a custom React hook useFetch<T>(url: string) that supports cancellation, caching, and loading/error states. Use AbortController."

Result: A typed hook that returns { data, error, loading, refetch }. It also prevents state updates after unmount.

const { data, error, loading, refetch } = useFetch<User>('/api/user');

3. Convert Class Component to Hooks

Prompt: "Refactor this class component to React hooks, preserving all behavior and passing existing tests."

Result: A clean functional component with useState and useEffect, eliminating this and lifecycle methods.

Node.js Utilities

4. Retry with Exponential Backoff

Prompt: "Write a typed retryAsync function that retries a promise on failure, using exponential backoff and jitter."

Result: A robust utility for network requests. The function accepts a callback and maxRetries, and calculates delay as 2^attempt * base + random jitter.

const result = await retryAsync(() => fetch(url), 3);

5. Debounce and Throttle

Prompt: "Implement debounce and throttle functions in TypeScript using setTimeout and Date.now()."

Result: Production-ready functions with clear signatures, usable for search inputs, resize handlers, and infinite scroll.

6. Watch a Directory and Run Compiler

Prompt: "Write a Node.js script using fs.watch that runs tsc --noEmit on every .ts file change."

Result: A tiny build watcher for development, useful for monorepos or custom tooling.

TypeScript Types

7. Union to Intersection

Prompt: "Define a TypeScript utility type UnionToIntersection<U> that converts a union type to an intersection type. Use infer and function parameter contravariance."

Result: A clever generic type often used to merge discriminated unions or to work with conditional types.

8. Type Guards for Discriminated Unions

Prompt: "Create type guard functions for a union of `Success

| Error | Pendingbased on thestatus` field."

Result: A set of isSuccess, isError, and isPending guards that narrow the type correctly.

9. Omit Sensitive Fields

Prompt: "Create a PublicUser type from the User interface, excluding password and email using Omit."

Result: A secure DTO-like type for API responses. This pattern, recommended by the TypeScript Handbook, prevents accidental data leaks.

Testing

10. Jest Tests for Debounce

Prompt: "Write Jest tests for the debounce function above, using fake timers and covering both leading and trailing invocations."

Result: A comprehensive test suite verifying timing and context binding.

11. React Testing Library for Counter

Prompt: "Create a React Testing Library test that verifies a counter increments on click and the decrement button is disabled at zero."

Result: A test file with render, fireEvent, and expect assertions. This covers the most common UI testing pattern.

Refactoring & Documentation

12. Convert Callbacks to Async/Await

Prompt: "Refactor this fs.readFile callback to async/await and handle errors with try/catch."

Result: Readable code that eliminates callback nesting and follows the modern Node.js style.

13. Code Smell Review

Prompt: "Review this snippet for anti-patterns like any, non-null assertions, and memory leaks. Suggest concrete fixes."

Result: A list of issues with corrected code. This prompt works as a lightweight code review tool.

14. Add JSDoc Comments

Prompt: "Write JSDoc for this function, including @param, @returns, and a usage example."

Result: Documentation that improves IDE intellisense and enforces better code contracts.

15. Generate API Client from OpenAPI

Prompt: "Generate a TypeScript fetch-based client from this OpenAPI spec, with full response types for all endpoints."

Result: A typed API layer that eliminates hand-written fetch calls and reduces runtime surprises.

Comparison Table

Category # Prompts Typical Use Case
React 3 Components, hooks, migration
Node.js 3 Utilities, scripts, watchers
TypeScript 3 Advanced types, guards, DTOs
Testing 2 Unit tests, component tests
Refactoring & Docs 4 Legacy code, docs, API clients

Tips for Getting Better Results

  • Include constraints: "strict mode", "no any", "use AbortController".
  • Provide minimal context: paste the existing code or a type definition.
  • Ask for alternatives: "Give me two implementations: memoized and non-memoized."
  • Iterate: The first output is a starting point. Use follow-up prompts like "simplify" or "add error handling".

For deeper understanding, consult the official React documentation on hooks, the TypeScript Handbook, and MDN Web Docs on AbortController. These sources define the patterns used in the prompts above.

Conclusion

These 15 prompts cover the most frequent code generation tasks in JavaScript and TypeScript. By copying and customizing them, you can accelerate development and keep code quality high. AI is not a replacement for understanding your codebase, but with these prompts it becomes a powerful pair programmer.

Try them today, adapt them to your project, and share your own favorite prompts with the hashtag #JSPrompts.

← All posts

Comments