10 Prompts for JavaScript and TypeScript Code Generation: React, Node.js, and Utilities

Introduction

Generating JavaScript and TypeScript code with AI has become a daily practice for many developers. Whether you are building a React component, a Node.js backend middleware, or a utility function for data transformation, the right prompt can save hours of manual work. According to the 2025 Stack Overflow Developer Survey, over 70% of professional developers now use AI coding assistants at least weekly, with JavaScript and TypeScript being the most common languages for such tasks (source: Stack Overflow Annual Developer Survey 2025).

This collection provides 10 ready-to-use prompts that cover real-world scenarios: React components with hooks, TypeScript generics, Node.js API endpoints, state management, data validation, and more. Each prompt is designed to be copy-pasted directly into your preferred AI tool (ChatGPT, Claude, or any code assistant). You will also see a concrete usage example and the generated output for each prompt, so you can understand exactly what to expect.

1. React Functional Component with TypeScript Props

Task: Generate a reusable React component with typed props, default values, and basic state management.

Prompt:

Create a TypeScript React functional component called UserProfileCard. It should accept props: name (string, required), age (number, optional, default 30), email (string, optional), and avatarUrl (string, optional). The component should display a card with an avatar image (fallback to a placeholder if not provided), the name, age, and email. Include a button that toggles the visibility of the email. Use React useState hook. Export the component as default.

Usage example:

Save the prompt as is. The AI will output something like:

import React, { useState } from 'react';

interface UserProfileCardProps {
  name: string;
  age?: number;
  email?: string;
  avatarUrl?: string;
}

const UserProfileCard: React.FC<UserProfileCardProps> = ({
  name,
  age = 30,
  email,
  avatarUrl
}) => {
  const [showEmail, setShowEmail] = useState(false);

  return (
    <div className="profile-card">
      <img
        src={avatarUrl || 'https://via.placeholder.com/100'}
        alt={name}
        style={{ width: 100, height: 100, borderRadius: '50%' }}
      />
      <h2>{name}</h2>
      <p>Age: {age}</p>
      {showEmail && email && <p>Email: {email}</p>}
      {email && (
        <button onClick={() => setShowEmail(!showEmail)}>
          {showEmail ? 'Hide Email' : 'Show Email'}
        </button>
      )}
    </div>
  );
};

export default UserProfileCard;

Why it works: The prompt specifies the component name, props with types and defaults, UI layout, and a specific React hook. This avoids ambiguity.

2. TypeScript Generic Utility Function

Task: Write a generic function that safely accesses nested object properties using dot notation.

Prompt:

Write a TypeScript generic function called getNestedValue<T, R> that takes an object of type T and a string path (like 'user.address.city') and returns the value at that path of type R | undefined. If any intermediate property is undefined, return undefined. Use recursion or reduce. Add proper type inference so that the return type is correctly inferred based on the path. Include JSDoc comments.

Usage example:

type User = {
  user: {
    address: {
      city: string;
      zip?: number;
    };
    name: string;
  };
};

const user: User = { user: { address: { city: 'New York', zip: 10001 }, name: 'Alice' } };
const city = getNestedValue<User, string>(user, 'user.address.city'); // string | undefined
console.log(city); // 'New York'

Why it works: The prompt explicitly asks for generics, type inference, and a specific use case (nested access).

3. Node.js Express Middleware for Authentication

Task: Create a JWT verification middleware for Express.js in TypeScript.

Prompt:

Generate a TypeScript middleware function for Express.js that verifies a JWT token from the Authorization header (Bearer scheme). If the token is valid, attach the decoded payload to req.user and call next(). If invalid or missing, return a 401 JSON response with an error message. Use the jsonwebtoken library. Import types from express. Export the middleware as default.

Usage example:

import express from 'express';
import authMiddleware from './authMiddleware';

const app = express();

app.get('/protected', authMiddleware, (req, res) => {
  res.json({ user: req.user });
});

Why it works: The prompt specifies the library, the exact behavior (401 on failure), and the type for req.user.

4. React Custom Hook for Fetching Data

Task: Build a reusable hook for fetching data with loading and error states.

Prompt:

Write a TypeScript custom React hook called useFetch<T> that takes a URL string as parameter. It should return an object with: data (T

| null), loading (boolean), error (string | null). Use useEffect to fetch data when the URL changes. Handle both successful and failed responses. If the response is not ok, throw an error. Clean up the fetch with AbortController on unmount.

Usage example:

interface Post {
  id: number;
  title: string;
}

const { data, loading, error } = useFetch<Post[]>('https://jsonplaceholder.typicode.com/posts');

if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return <ul>{data?.map(post => <li key={post.id}>{post.title}</li>)}</ul>;

Why it works: The prompt defines a generic hook, specifies the return type, and includes cleanup logic — a real-world best practice.

5. TypeScript Enum and Type Guard

Task: Create an enum for order statuses and a type guard function.

Prompt:

Define a TypeScript enum called OrderStatus with values: Pending, Shipped, Delivered, Cancelled. Then write a function isOrderCompleted(status: OrderStatus): boolean that returns true only if status is Delivered or Cancelled. Finally, write a type guard function isShippedOrder(status: unknown): status is OrderStatus.Shipped that checks if the value is exactly OrderStatus.Shipped.

Usage example:

const status: unknown = 'Shipped';
if (isShippedOrder(status)) {
  // TypeScript now knows status is OrderStatus.Shipped
  console.log('Order is shipped');
}

Why it works: The prompt combines enum definition with a practical type guard, which is common in TypeScript codebases.

6. Zod Schema for Form Validation

Task: Generate a Zod schema for a registration form with custom error messages.

Prompt:

Create a Zod schema called registerSchema for a user registration form with fields: username (string, min 3, max 20, regex only alphanumeric), email (string, email format), password (string, min 8, must contain at least one uppercase, one lowercase, one digit), and confirmPassword (string). Add a refinement that checks confirmPassword matches password. Include custom error messages for each validation rule.

Usage example:

import { z } from 'zod';

const registerSchema = z.object({
  username: z.string()
    .min(3, 'Username must be at least 3 characters')
    .max(20, 'Username must be at most 20 characters')
    .regex(/^[a-zA-Z0-9]+$/, 'Username must be alphanumeric'),
  email: z.string().email('Invalid email format'),
  password: z.string()
    .min(8, 'Password must be at least 8 characters')
    .regex(/[A-Z]/, 'Password must contain an uppercase letter')
    .regex(/[a-z]/, 'Password must contain a lowercase letter')
    .regex(/[0-9]/, 'Password must contain a digit'),
  confirmPassword: z.string()
}).refine(data => data.password === data.confirmPassword, {
  message: 'Passwords do not match',
  path: ['confirmPassword']
});

Why it works: The prompt explicitly asks for custom messages and refinement, which is exactly what production forms need.

7. React Redux Toolkit Slice

Task: Generate a Redux Toolkit slice for a shopping cart.

Prompt:

Write a Redux Toolkit slice called cartSlice with initial state: items (array of {id: number, name: string, quantity: number, price: number}), totalItems (number), totalPrice (number). Create reducers: addItem (add or increment quantity), removeItem (remove by id), clearCart. Use createAsyncThunk for a hypothetical fetchCart action that simulates an API call returning dummy data. Export the slice and its actions.

Usage example:

import { useDispatch, useSelector } from 'react-redux';
import { addItem, removeItem, clearCart } from './cartSlice';

const dispatch = useDispatch();
dispatch(addItem({ id: 1, name: 'Laptop', quantity: 1, price: 999 }));

Why it works: The prompt covers both synchronous reducers and an async thunk, which is typical for real Redux usage.

8. TypeScript Utility Type for API Response

Task: Define a generic API response wrapper type.

Prompt:

Define a TypeScript type called ApiResponse<T> that has properties: success (boolean), data (T

| null), error (string | null), and timestamp (number, Unix timestamp in milliseconds). Then create a helper function createSuccessResponse<T>(data: T): ApiResponse<T> and createErrorResponse(error: string): ApiResponse<null>. Both should set the timestamp to Date.now().

Usage example:

const success = createSuccessResponse({ user: 'Alice' });
// success: { success: true, data: { user: 'Alice' }, error: null, timestamp: 1721400000000 }

const error = createErrorResponse('Not found');
// error: { success: false, data: null, error: 'Not found', timestamp: 1721400000000 }

Why it works: The prompt includes a generic type and two factory functions — exactly what you need for consistent API handling.

9. Node.js File Upload with Multer and TypeScript

Task: Create an Express route for single file upload with size and type validation.

Prompt:

Write a TypeScript Express route for uploading a single image file using multer. Configure multer with: storage to disk in './uploads/' folder, file filter to allow only image/jpeg and image/png, and limit file size to 2MB. The route should accept POST at '/upload' and return the file path on success. If validation fails, return a 400 error with a descriptive message.

Usage example:

// POST /upload with multipart/form-data and field name 'image'
// Returns { path: '/uploads/123.jpg' } or error

Why it works: The prompt specifies the storage, filter, and limit — all critical for a production upload endpoint.

10. React Context with useReducer

Task: Build a theme context with a reducer for toggling dark/light mode.

Prompt:

Create a React context called ThemeContext that provides a theme string ('light' | 'dark') and a dispatch function. Use useReducer to manage state. The reducer should handle two actions: TOGGLE_THEME (switch between light and dark) and SET_THEME (set a specific theme). Export the context provider and a custom hook useTheme that throws an error if used outside the provider.

Usage example:

function App() {
  return (
    <ThemeProvider>
      <ThemedComponent />
    </ThemeProvider>
  );
}

function ThemedComponent() {
  const { theme, dispatch } = useTheme();
  return (
    <div style={{ background: theme === 'dark' ? '#333' : '#fff' }}>
      <button onClick={() => dispatch({ type: 'TOGGLE_THEME' })}>Toggle</button>
    </div>
  );
}

Why it works: The prompt combines context, useReducer, and a custom hook with validation — a common pattern in React apps.

Conclusion

These 10 prompts cover the most frequent JavaScript and TypeScript code generation tasks in modern web development. By using specific, well-structured prompts, you can significantly reduce boilerplate writing and focus on business logic. Remember to always review generated code for security and correctness, especially when dealing with authentication or file uploads.

Start by copying any prompt from this list into your favorite AI assistant and adjust the details to your project. The more context you provide (like library versions or coding style), the better the output. Happy coding!

← All posts

Comments